C# equivalent of the IsNull() function in SQL Server

前端 未结 10 2093
太阳男子
太阳男子 2020-12-12 21:53

In SQL Server you can use the IsNull() function to check if a value is null, and if it is, return another value. Now I am wondering if there is anything similar

10条回答
  •  盖世英雄少女心
    2020-12-12 22:01

    I've been using the following extension method on my DataRow types:

        public static string ColumnIsNull(this System.Data.DataRow row, string colName, string defaultValue = "")
        {
            string val = defaultValue;
            if (row.Table.Columns.Contains(colName))
            {
                if (row[colName] != DBNull.Value)
                {
                    val = row[colName]?.ToString();
                }
            }
            return val;
        }
    

    usage:

    MyControl.Text = MyDataTable.Rows[0].ColumnIsNull("MyColumn");
    MyOtherControl.Text = MyDataTable.Rows[0].ColumnIsNull("AnotherCol", "Doh! I'm null");
    

    I'm checking for the existence of the column first because if none of query results has a non-null value for that column, the DataTable object won't even provide that column.

提交回复
热议问题