Reputation: 1733
I have a datatable and I want to get the values that is not null or empty in one column.
This is my 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);
}
In this table, you can see Amy and Jessica's position is empty. When I am looping through this table, how can I get the string value that is not null in the position column? Help will be appreciated. Thanks
Upvotes: 0
Views: 13502
Reputation:
Try this
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);
}
Upvotes: 2
Reputation: 9739
Try this -
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
}
}
Upvotes: 1
Reputation: 448
Maybe This code help you:
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);
}
using:
result.OfficeID = GlobalUtilities.GetReaderValue<int>(reader, "OfficeID");
Upvotes: 0