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:
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user