How to Edit a row in the datatable

前端 未结 6 1027
说谎
说谎 2020-12-05 18:46

I have created a data table. It has 3 column Product_id, Product_name and Product_price

    Datatable tabl         


        
相关标签:
6条回答
  • 2020-12-05 18:51

    If your data set is too large first select required rows by Select(). it will stop further looping.

    DataRow[] selected = table.Select("Product_id = 2")
    

    Then loop through subset and update

        foreach (DataRow row in selected)
        {
            row["Product_price"] = "<new price>";
        }
    
    0 讨论(0)
  • 2020-12-05 18:52

    You can traverse through the DataTable like below and set the value

    foreach(DataTable thisTable in dataSet.Tables)
    {
        foreach(DataRow row in thisTable.Rows)
        {
            row["Product_name"] = "cde";
        }
    }
    

    OR

    thisTable.Rows[1]["Product_name"] = "cde";
    

    Hope this helps

    0 讨论(0)
  • 2020-12-05 18:56

    First you need to find a row with id == 2 then change the name so:

    foreach(DataRow dr in table.Rows) // search whole table
    {
        if(dr["Product_id"] == 2) // if id==2
        {
            dr["Product_name"] = "cde"; //change the name
            //break; break or not depending on you
        }
    }
    

    You could also try these solutions:

    table.Rows[1]["Product_name"] = "cde" // not recommended as it selects 2nd row as I know that it has id 2
    

    Or:

    DataRow dr = table.Select("Product_id=2").FirstOrDefault(); // finds all rows with id==2 and selects first or null if haven't found any
    if(dr != null)
    {
        dr["Product_name"] = "cde"; //changes the Product_name
    }
    
    0 讨论(0)
  • 2020-12-05 18:57

    You can find that row with

    DataRow row = table.Select("Product_id=2").FirstOrDefault();
    

    and update it

    row["Product_name"] = "cde";
    
    0 讨论(0)
  • 2020-12-05 19:07

    Try this I am also not 100 % sure

            for( int i = 0 ;i< dt.Rows.Count; i++)
            {
               If(dt.Rows[i].Product_id == 2)
               {
                  dt.Rows[i].Columns["Product_name"].ColumnName = "cde";
               }
            }
    
    0 讨论(0)
  • 2020-12-05 19:09

    Try the SetField method:

    By passing column object :

    table.Rows[rowIndex].SetField(column, value);
    

    By Passing column index :

    table.Rows[rowIndex].SetField(0 /*column index*/, value);
    

    By Passing column name as string :

    table.Rows[rowIndex].SetField("product_name" /*columnName*/, value);
    
    0 讨论(0)
提交回复
热议问题