Reputation: 2041
I have generic list ... I am trying to convert it to a data table.
I am using below code..
private DataTable ToDataTable<T>(List<T> items)
{
var tb = new DataTable(typeof(T).Name);
PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in props)
{
Type t = GetCoreType(prop.PropertyType);
tb.Columns.Add(prop.Name, t);
}
foreach (T item in items)
{
var values = new object[props.Length];
for (int i = 0; i < props.Length; i++)
{
values[i] = props[i].GetValue(item, null);
}
tb.Rows.Add(values);
}
return tb;
}
I need to add another column in that datatable, say StatusText
.
There is already a column in that datatable called Status
.
If this column is 0 then StatusText
should be Active
, or if it is 1 then StatusText
will be Inactive
Like my code returns below table currently...
Id Name Status
------------------
1 Test 1
2 Test1 0
3 Test2 0
But, how can I generate table like below?
Id Name Status StatusText
------------------------------
1 Test 1 InActive
2 Test1 0 Active
3 Test2 0 Active
Upvotes: 1
Views: 9326
Reputation: 3204
Just add this in your class defenition:
public string StatusText
{
get
{
if(status == 0)
return "Active";
else
return "InActive";
}
}
Upvotes: 0
Reputation: 9869
Try this
DataTable dt = ToDataTable(your list); // Get DataTable From List
dt.Columns.Add(new Column("StatusText", typeof(string))); // Add New Column StatusText
//Iterate All Rows
foreach(DataRow row in dt.Rows)
{
//Check Status value, and set StatusText accordingly.
row["StatusText"] = int.Parse(row["Status"])==1 ? "InActive" : "Active";
}
Upvotes: 1