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"

3
  • Possible duplicate of How to remove rows from DataGridView? Commented Oct 24, 2019 at 7:49
  • the rows aren't manually selected, the rows are to be selected based on the change in textbox Commented Oct 24, 2019 at 7:53
  • It still shows how to remove a row.. Commented Oct 24, 2019 at 7:54

2 Answers 2

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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");
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.