简体   繁体   中英

updating existing row in a DataTable

iam developing a invoice program

in invoice form i have textboxes and a datagridview here is my sample code

DataTable dt = new DataTable();
dt.Columns.Add("productCode");
dt.Columns.Add("qty");
dt.Columns.Add("price");
dt.Columns.Add("total");
string prodCode = txtProductCode.Text;
decimal qty = Convert.ToInt32(txtQty.Text);
decimal price = Convert.ToInt32(txtPrice.Text);
decimal total = qty*price;
dt.Rows.Add(prodCode,qty,price,total);
dataGridView1.DataSource = dt;

what i want to do is if i add same prodCode again i want to update qty and total in existing row instead of add new row

Using strongly typed datasets would make parts of this easier (Actually, they nearly always make all work with datatable and dataset easier; I would use them by default)

I would perform the following steps:

  • Add a DataSet to your project
  • Add a table to it (open it in the visual designer, right click the surface, add a datatable)
  • Add your columns to the table and choose their data types (string, decimal etc) - right click the datatable and choose "add column"
  • Right click the prodCode column and set it to be the primary key
  • Set the Expression property of the Total column to be [Qty] * [Price] - it will now auto-calculate itself, so you don't need to do the calc in your code

In your code:

string prodCode = txtProductCode.Text;
decimal qty = Convert.ToInt32(txtQty.Text);
decimal price = Convert.ToInt32(txtPrice.Text);

//does the row exist?
var ro = dt.FindByProdCode(prodCode); //the typed datatable will have a FindByXX method generated on whatever column(s) are the primary key

if(ro != null){
  ro.Price = price; //update the existing row
  ro.Qty += qty;
} else {
  dt.AddXXRow(prodCode, qty, price); //AddXXRow is generated for typed datatables depending on the table name
}

If you have a back end database related to these datatables, you life will get a lot easier if you connect your dataset to the database and have visual studio generate mappings between the dataset and the tables in the database. The TableAdapters it generates take the place of generic DataAdapters, and manage all the db connections, store the SQLs that retrieve and update the db etc.

You can use DataTable.NewRow() method to have a reference to the new row.

var rowNew = dt.NewRow()
...
dt.AddRow(rowNew);

Prefer using strong typed DataTable if the schema is not generated at runtime.

Also you can find an existing row using:

int found = -1;
for (int index = 0; i < dt.Count; index++)
{
  if ( !condition ) continue;
  found = index;
  break;
}

Or use the Find() method.

You can loop the whole datagridview rows and check if there is existing row with same new row product code, if yes update the columns you want of this row. This is not tested but something like this:

    string prodCode = txtProductCode.Text;
    decimal qty = Convert.ToInt32(txtQty.Text);
    decimal price = Convert.ToInt32(txtPrice.Text);
    decimal total = qty*price;

    bool isRowExist = false;

    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        if (row.Cells[0].Value.ToString().Equals(prodCode))
        {
            var totalQty = Convert.ToInt32(row.Cells[1].Value.ToString()) + qty ;
            var updateTotal = Convert.ToInt32(row.Cells[3].Value.ToString()) + total  ;

            row.Cells[1].Value = totalQty;
            row.Cells[3].Value = total; 

            isRowExist = true
        }
    }

    if(!isRowExist)
        dt.Rows.Add(prodCode,qty,price,total);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM