Reputation: 1019
I have 2 datagridviews in c#. Lets call them dgv1 and dgv2. dgv1 is bound to DataTable dt1 which is populated from SQL server. dgv2 is bound to DataTable dt2. dt2 is populated by copying rows from dt1 on Enter.
In dt2 I have one additional column 'QUantity' which should be increased when user wants to add row which already exists.
Code to copy row from dt1 to dt2:
DataRowView currentDataRowView = (DataRowView)dgv1.CurrentRow.DataBoundItem;
DataRow dr = currentDataRowView.Row;
dt2.ImportRow(dr);
dgv2.DataSource = dtInvoiceItems;
How to check if row already exists in dt2 based one column which is primary and increase quantity if it does exist or importrow if it does not?
Upvotes: 0
Views: 763
Reputation: 14059
To find row by the primary key: DataRow row = dt2.Rows.Find(primary_key_value);
where primary_key_value
can be obtained by dr[dt2.PrimaryKey[0]]
.
To increase quantity: row["QUantity"] = (int)row["QUantity"] + 1;
.
The resulting code:
DataRowView currentDataRowView = (DataRowView)dgv1.CurrentRow.DataBoundItem;
DataRow dr = currentDataRowView.Row;
DataRow row = dt2.Rows.Find(dr[dt2.PrimaryKey[0].ColumnName]);
if (row == null)
dt2.ImportRow(dr);
else
row["QUantity"] = (int)row["QUantity"] + 1;
EDIT Error fixed
Upvotes: 1