开发者

DataGridView.Rows.RemoveAt(int index) doesn't remove row in windows form? [duplicate]

This question already has answers here: C# - how do I refresh DataGridView after removing rows (8 answers) Closed 8 years ago.
int i = dataGridView1.CurrentRow.Index;
dataGridView1.Rows.RemoveAt(i);

The above code for deleting cur开发者_Python百科rent selected row (only allow to select 1 row) but I still can see the row remains in datagridview. Did I miss an update or invalidate ?

ps: dataGridView1 is data-bound.

ps2: I use linq query to bind data and I don't want to query again for just to show a row was deleted, I think it will slow down performance.


I think the solution depends on how you bind the data. If you are binding a BindingList, RemoveAt() method removes handles everything for you and you don't have to refresh the DataGridView.

Try below and see...

dataGridView1.Refresh();

OR re-bind the data and see..

dataGridView1.DataSource = myDataSource;
dataGridView1.Refresh();


remove the item from the datasource, and bind again.

since the data comes from linq, before binding, you can do:

var result = fooLinq.ToList();
dataGridView1.DataSource = result;


//to remove and bind again
var result = dataGridView1.DataSource as List<FooType>;
result.RemoveAt(fooIndex);
dataGridView1.DataSource = result;


If I understand you correctly, you want to delete rows selected by a user from your DGV.

  1. Use the DataGridViewRowCollection of your DGV rather than the DataRowCollection of the DataTable. The DataGridViewRow has the Selected property that indicates whether a row is selected or otherwise.

  2. Once you have determined that a row is to be deleted, you can use the Remove method of the DataGridViewRowCollection to delete the item from the grid, e.g. YerDataGridView.Rows.Remove(row)

  3. Note that at this point, although the item is removed from the DGV, it still has not been deleted from the Access DB. You need to call the TableAdapter Update method on your DataSet/DataTable to commit the deletions to the DB, e.g. YerTableAdapter.Update(YerDataSet)

I normally would call Update once to commit the changes only after having removed all the items to be deleted from the DGV.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜