如何在数据表列中获取非null值

时间:2016-05-03 06:18:19

标签: c# datatable

我有一个数据表,我想在一列中获取非空或空的值。

这是我的数据表(dt)

emp_id     emp_name      gender       Position
1          Peter         M            Trainee
2          Amy           F            
3          Jessica       F
4          Josh          M            Clark
5          Tony          M            Manager



  DataTable dt = new DataTable();

   dt.Columns.Add("emp_name", typeof(string));
   dt.Columns.Add("gender", typeof(string));
   dt.Columns.Add("Position", typeof(string));


   foreach(DataRow row in dt.Rows){
        //get the values in position column that is not null (This does not work)
        string position = row.Field<string>(2);

   }

在此表中,您可以看到Amy和Jessica的位置为空。当我循环遍历此表时,如何在位置列中获取非空值的字符串值?帮助将不胜感激。谢谢

3 个答案:

答案 0 :(得分:2)

试试这个

  DataTable dt = new DataTable();

  dt.Columns.Add("emp_name", typeof(string));
  dt.Columns.Add("gender", typeof(string));
  dt.Columns.Add("Position", typeof(string));

  DataRow[] result = dt.Select("Position != null and Position != ''");
  foreach (DataRow row in result)
  {
      string position = row.Field<string>(2);
  }

答案 1 :(得分:1)

试试这个 -

        foreach (DataRow row in dt.Rows)
        {
            //get the values in position column that is not null (This does not work)
            var position = row.Field<string>("Position");

            if (string.IsNullOrEmpty(position))
            {
                //Null or empty
            }
            else
            {
                //Not null
            }

        }

答案 2 :(得分:0)

也许这段代码可以帮助您:

public static T GetReaderValue<T>(SqlDataReader reader, string fieldName)
        {
            if (reader != null && reader[fieldName] != null)
            {
                object value = reader[fieldName];
                if (value is DBNull)
                    return default(T);
                return (T)reader[fieldName];
            }
            return default(T);
        }

使用:

result.OfficeID = GlobalUtilities.GetReaderValue<int>(reader, "OfficeID");