Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the DataTable Column Value without looping?

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.

like image 543
thevan Avatar asked Aug 24 '11 06:08

thevan


4 Answers

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();
}
like image 149
shenhengbin Avatar answered Oct 21 '22 00:10

shenhengbin


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);
like image 44
Nishantha Avatar answered Oct 21 '22 02:10

Nishantha


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

like image 2
CharithJ Avatar answered Oct 21 '22 02:10

CharithJ


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.

like image 1
Davide Piras Avatar answered Oct 21 '22 00:10

Davide Piras