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);
}
}
CodePudding user response:
Here's what might be the problem: You are iterating a collection datagriddataGridView2.Rows
but while you're iterating it, you change it by removing a row. The trick to preventing this being a problem is to capture the collection to an array. This means you'll be iterating a copy that isn't going to change and then you're free to delete objects from the Rows collection.
Try this minor change and see if it helps:
foreach (DataGridViewRow row in dataGridView2.Rows.Cast<DataGridViewRow>().ToArray())
{
if (row.Cells[0].Value.ToString().Equals(textBox1.Text))
{
MessageBox.Show("Match deleted");
dataGridView2.Rows.Remove(row);
}
}
You may need to add this reference:
using System.Linq;
CodePudding user response:
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!
CodePudding user response:
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();
}