I have a DataTable which has 4 columns. I want to change the 3rd column's value as "0". Below is my DataTable.
ID Name Value Type
---- ---- ----- -----
1 Sam 250 2
2 Rai 324 3
3 Tim 985 8
My Desired Result should be like below:
ID Name Value Type
---- ---- ----- ------
1 Sam 0 2
2 Rai 0 3
3 Tim 0 8
How to achieve this without looping? Any suggestions please.
How about this? ↓ without loop....
static void Main(string[] args)
{
DataTable table = new DataTable();
table.Columns.Add("col1");
table.Columns.Add("col2");
table.Rows.Add(new object[] { "1", "1" });
table.Rows.Add(new object[] { "1", "1" });
table.Rows.Add(new object[] { "1", "1" });
table.Rows.Add(new object[] { "1", "1" });
foreach (DataRow row in table.Rows)
Console.WriteLine(row["col2"].ToString());
Console.WriteLine("***************************************");
DataColumn dc = new DataColumn("col2");
dc.DataType = typeof(int);
dc.DefaultValue = 0;
table.Columns.Remove("col2");
table.Columns.Add(dc);
foreach (DataRow row in table.Rows)
Console.WriteLine(row["col2"].ToString());
Console.ReadKey();
}
You can use a simple trick here. Delete row and re-add it to the table.
dt.Columns.Remove("Value");
dt.Columns.Add("Value", type(System.Int32), 0);
DataRow[] rows = myDataTable.Select("id = 'myIdValue');
//If you don't want to select a specific id ignore the parameter for select.
for(int i = 0; i < rows.Length; i ++)
{
rows[i]["value"] = 0;
}
DataTable.Select Method
if you know the ID you can simply filter for it using Select or Find (not remember exactly but I think is Select), once you have the row, you can assign column values.
I am sure there is also a better LINQ oriented way but this old school ADO.NET/System.Data approach should work anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With