From 0aba9e91e2e47b726702a3c6d2a7397128aa8f81 Mon Sep 17 00:00:00 2001 From: TekH Date: Wed, 25 Feb 2026 16:39:55 +0100 Subject: [PATCH] Add DataRowExtensions for safe value retrieval with defaults Introduced DataRowExtensions.cs with extension methods for DataRow: - ItemEx: Retrieves a value by column name with a default if missing or null. - ItemEx (string): Overload for string values, using the generic method. These methods help prevent errors when accessing missing or null columns. --- .../Extensions/DataRowExtensions.cs | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 EnvelopeGenerator.ServiceHost/Extensions/DataRowExtensions.cs diff --git a/EnvelopeGenerator.ServiceHost/Extensions/DataRowExtensions.cs b/EnvelopeGenerator.ServiceHost/Extensions/DataRowExtensions.cs new file mode 100644 index 00000000..b5fa51c3 --- /dev/null +++ b/EnvelopeGenerator.ServiceHost/Extensions/DataRowExtensions.cs @@ -0,0 +1,27 @@ +using System.Data; + +namespace EnvelopeGenerator.ServiceHost.Extensions; + +public static class DataRowExtensions +{ + public static T ItemEx(this DataRow row, string columnName, T defaultValue) + { + if (!row.Table.Columns.Contains(columnName)) + { + return defaultValue; + } + + var value = row[columnName]; + if (value is DBNull or null) + { + return defaultValue; + } + + return (T)Convert.ChangeType(value, typeof(T)); + } + + public static string ItemEx(this DataRow row, string columnName, string defaultValue) + { + return row.ItemEx(columnName, defaultValue); + } +} \ No newline at end of file