'how to remove a datagridview row that has your textbox text value with a loop?
so i have this datagridview2 that i'm using it for searching.
and when i search and find the row that i want i click on that row, and all the values go to textboxes, and there is a button that deletes the record on click using the id on textbox 1,
in another datagridview1 i have a method that refreshes the whole datagridview records when i delete that item by its id.
so back to datagridview2, i want when i delete that row, the row gets deleted also from datagridview, without using and refreshing my datagridview with my refilldatagridview() method that i created,
when i use dataGridView2.Rows.Remove(row);
it works without loop, as well as the removeAt index
the problem is in the loop it never enters the if and i don't know why
foreach (DataGridViewRow row in dataGridView2.Rows)
{
if (row.Cells[0].Value.ToString().Equals(textBox1.Text))
{
MessageBox.Show("Match deleted");
dataGridView2.Rows.Remove(row);
}
}
Solution 1:[1]
I don't know if this is what you're pointing out.
Using LINQ (try column name instead of column index, it's getting error if I use column index)
dataGridView1.Rows.RemoveAt(dataGridView1.Rows.Cast<DataGridViewRow>().Where(w => w.Cells["Value1"].Value.ToString() == textBox1.Text).Select(s => s.Index).FirstOrDefault());
dataGridView2.Rows.RemoveAt(dataGridView2.Rows.Cast<DataGridViewRow>().Where(w => w.Cells["Value1"].Value.ToString() == textBox1.Text).Select(s => s.Index).FirstOrDefault());
Just place the 2 line of code above inside of your loop.
I hope it helps!
Solution 2:[2]
I think there have Several way that u can try
#1 simple iteration
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
if (dataGridView2[i].Cells[0].Value.ToString().Equals(textBox1.Text))
dataGridView2.Rows.Remove(dataGridView2[i]);
}
#2 If u want to use dataTable to search
var query = dTable.AsEnumerable().Where(r => r.Field<string>(columnName) == textBox1.Text);
foreach(var row in query.ToList())
{
row.Delete();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | once ng kahirapan |
| Solution 2 | zyrastory |


