I want to add or updates rows in a blank DataGridView that is bind to a DataTable.
My DataTable has 3 column FName, LName, Number.
Also I have 3 TextBox for entering data of those columns and a Button of AddOrUpdate.
The add or update operation should follow this rule (in pseudo code):
If the item has been added before and already exists in DataTable Then
Update the value of 'Number' Column .
ELSE
Add new row using given values.
And here is my code to do so:
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if ((row.Cells[1].Value.ToString().Equals(txt_Name.Text)) && (row.Cells[2].Value.ToString().Equals(txt_Family.Text)))
{
row.Cells[3].Value = txt_Number.Text;
dataGridView1.DataSource = dt;
break;
}
else
{
dt.Rows.Add(txt_Code.Text, txt_Name.Text, txt_Family.Text, txt_Number.Text);
dataGridView1.DataSource = dt;
break;
}
}
Using my code, there are two problems:
- First row could not be added by below code (no error). (First row should be added by another button or default value.)
- Compare to find a existent row similar to the row being added, played only the first row of the DataGridView.
How can I do search in DatTable and perform and Add Or Update?