开发者

How to change the DataTable Column Value without looping?

开发者 https://www.devze.com 2023-03-30 13:51 出处:网络
I have a DataTable which has 4 columns. I want to change the 3rd column\'s value as \"0\". Below is my DataTable.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消