2

A row is to be added in a datagridview when the value of the text box is changed. The same row is to be deleted when the value of the text box gets back to 0.

The data is added, but I don't know how to delete records from the datagrid view based on a condition.

private void textBox1_TextChanged(object sender, EventArgs e)
{
    value = Convert.ToInt32(textBox1.Text);

    if (value == 2)
    {
      string[] row1 = { "Value is 2" }; //column name is column1
      dataGridView1.Rows.Add(row1);
    }

   if (value == 0)
    {
      // code to delete the row when Value is equal to 0 and the 
      //condition is data in column1 of datagridView = "Value is 2"
    }
}

Can anyone please help me how to delete the row/rows in dataGridView1?

With the condition, data in column1 of dataGridView1 is "Value is 2"

impulse101
  • 99
  • 1
  • 10

2 Answers2

0

Store the index of the added row to make sure you delete the right row and also to only delete the last added row.

int connectedRowId = -1;
private void textBox1_TextChanged(object sender, EventArgs e)
{
    value = Convert.ToInt32(textBox1.Text);

    if (value == 2)
    {
      string[] row1 = { "Value is 2" }; //column name is column1
      connectedRowId  = dataGridView1.Rows.Add(row1);
    }

   if (value == 0)
    {
      dataGridView1.Rows.RemoveAt(connectedRowId);
    }
}
demoncrate
  • 390
  • 2
  • 14
0

You can loop the rows and find by value:

private void textBox1_TextChanged(object sender, EventArgs e)
{
    value = Convert.ToInt32(textBox1.Text);

    if (value == 2)
    {
        string[] row1 = { "Value is 2" }; //column name is column1
        dataGridView1.Rows.Add(row1);
    }

    if (value == 0)
    {
        dataGridView1.Rows.RemoveAll(row => row.Cells[0].Value == "Value is 2");
    }
}
Huseyin Yagli
  • 9,896
  • 6
  • 41
  • 50