Add DataRowExtensions for safe value retrieval with defaults

Introduced DataRowExtensions.cs with extension methods for DataRow:
- ItemEx<T>: 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.
This commit is contained in:
2026-02-25 16:39:55 +01:00
parent 1a0973075b
commit 0aba9e91e2

View File

@@ -0,0 +1,27 @@
using System.Data;
namespace EnvelopeGenerator.ServiceHost.Extensions;
public static class DataRowExtensions
{
public static T ItemEx<T>(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<string>(columnName, defaultValue);
}
}