Add value (Row) if not exists already in the gridview

10,944

I guess that your DataGridView has two columns (?). So if you would like to check whether some row contains the first column string, you can do like this:

UPDATED according to OP comment:

boolean found = false;
foreach (DataGridViewRow row in dgv_standards)
{
    if (row.Cells[0].Value == cbo_standard.SelectedValue.ToString())
    {
        // row exists
        found = true;
        MessageBox.Show("Row already exists");
        break;
    }
}

if (!found)
{
    dgv_standards.Rows.Add(cbo_standard.SelectedValue.ToString(), cbo_standard.Text);
}

Similar for second row, with row.Cells[1].

Share:
10,944
user3213767
Author by

user3213767

Updated on June 05, 2022

Comments

  • user3213767
    user3213767 almost 2 years

    I want to add some rows in datagridview (without binding) from a combobox text property. but I need first to check if it is already added, it yes then show a message, if not already added, then add the text value of the combo in the gridview. I am using VS 2010 with C# I search a lot of all available solutions but not working with me.

    I tried to loop on the rows but I couldn't do it,, please help!!

    this is my code to add the value but how to check?

    dgv_standards.Rows.Add(cbo_standard.SelectedValue.ToString(), cbo_standard.Text);
    
    • Raja Nadar
      Raja Nadar about 10 years
      why can't you loop on the rows? how are you accessing the per row cell values? what error do you see?
    • user3213767
      user3213767 about 10 years
      thanks for replying, your idea is clear but if the row exist then simple message and break, BUT if ( is not exist) then add row . imagine if the existing row in the third position, then the loop will check the first row(which is already not equal), so it will add new row, but the reality the existing row in the third position
  • user3213767
    user3213767 about 10 years
    thanks for replying, your idea is clear but if the row exist then simple message and break, BUT if ( is not exist) then add row . imagine if the existing row in the third position, then the loop will check the first row(which is already not equal), so it will add new row, but the reality the existing row in the third position
  • etaiso
    etaiso about 10 years
    @user3213767 Hold a boolean that is initialized to false. First run all over your rows, if one of them is what you are looking for, set it to true and break. Next code will be to test the boolean value, if it's false, you can add the row, otherwise, continue.
  • user3213767
    user3213767 about 10 years
    Thanks alot. Best !!! ..really thanks... can you mark the questios as answered and vote, because i cant do it for my low reputation number
  • etaiso
    etaiso about 10 years
    @user3213767 No I can't mark my own question as the accepted answer and neither to up vote it .. I think you should be able to mark as answer (did you try clicking on the 'V'?).