简体   繁体   中英

How to check if a column value is null in a datatable in C#?

So what i'm trying to do, is to loop through the datatable's column to get the value out of it.

For example, this is my datatable

emp_id      f_name         email            remarks
1            Jim          Jim@yahoo.com
2            Apple        apple@gmail.com  
3            Peter
4            Amy          amy@gmail.com

In this datatable, you can see that Peter's email is missing. I want to retrieve this record set a values in remarks "No email".

How can I do this?

Try this query, so you don't have to retrieve and modify the DataTable:

select  emp_id,
        f_name,
        email,
        ISNULL(email,'No Email') AS 'remark'
from [tablename]

if you want to retrieve only the null email add where in the query like this

 select  emp_id,
            f_name,
            email,
            ISNULL(email,'No Email') AS 'remark'
    from [tablename] where email is null

if you are using MySQL, replace ISNULL to IFNULL

You can easily achieve this in LINQ:

var noemaillist = (from m in databaseContext.TableName
                  where m.email == String.Empty
                  select m).ToList();
if(noemaillist != null)
{
   foreach(var item in noemaillist)
   {
      item.remarks = "No email";
   }
}
databaseContext.SubmitChanges();

This will return the list with empty email id's and set the remarks column to "No email" for the corresponding empty email fields.

foreach(DataRow dr in dt.Select("email is NULL or email=''"))
{
   dr["Remarks"]="No Email";
}
dt.AcceptChanges();

The above will set value of column "Remarks" as required.

在ADO.NET中,具有IsDBNull(<column>)属性,在LINQ中,您可以通过email != NULL检查它email != NULL

  foreach (DataColumn col in dataTable.Columns)
            {
                foreach (DataRow row in dataTable.Rows)
                {
                  var x=row[col.ColumnName].ToString();
                  if (string.IsNullOrEmpty(x))
                  {
                      var colName = col.ColumnName.ToString();
                      row["remarks"] = string.Format("{0} is required", colName);
                  }

                }
            } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM