Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Good day;
I want to add row in blank DataGridView by DataTable, this adding should follow 1 rule(in pseudo code):
"IF item before added, update 'Number' cell by refrenced TextBox (DataGridView Cell's: FName, LName, Number) ELSE add new row".

But there are two problems:
1. First row could not be added by below code (no error).
(first row should be add by another button or default value)
2. Compare to find an existent row similar to the row being added, played only the first row of the DataGridView.

C#
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;          
    }
}
Posted
Updated 29-Aug-15 6:29am
v2

1 solution

I was looking this:
C#
try
{
    for (int i = 0; i < dataGridView1.RowCount; i++)
    {
        if (dataGridView1.Rows[i].Cells[0].Value.ToString() == txt_FName.Text)
        {
            dataGridView1.Rows[i].Cells[2].Value = [any proccess] ; // Update Row
            return;
        }
    }
}
catch(Exception ex)
{
    MessageBox.Show(ex.Message);
}
dataGridView1.Rows.Add(txt_FName.Text, txt_LName.Text, txt_Number.Text); // New Row
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900