8

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.

thevan
  • 10,052
  • 53
  • 137
  • 202

4 Answers4

14

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();
}
shenhengbin
  • 4,236
  • 1
  • 24
  • 33
5

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);
Nishantha
  • 6,065
  • 6
  • 33
  • 51
2
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

CharithJ
  • 46,289
  • 20
  • 116
  • 131
1

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.

Davide Piras
  • 43,984
  • 10
  • 98
  • 147
  • But Select is only to filter the datatable by giving its column value. How can I set the value as "0" for all the column values? – thevan Aug 24 '11 at 06:49
  • thank u so much for your valuable contribution to my question. – thevan Aug 24 '11 at 07:04