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.
27 lines
664 B
C#
27 lines
664 B
C#
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);
|
|
}
|
|
} |