пятница, 18 января 2013 г.

Remove rows from DataGridView

Today I faced with funny bug.
Once I set some collection as DataSource for DataGridView, the collection becomes read-only and I can't remove anything from there.

I needed just to remove selected rows from DataGridView. And I've tried to do that with very straightforward way:
dataGridView1.SelectedRows.Clear();
And got exception:
System.NotSupportedException: Operation not supported. Collection is read-only.

Workaround I found is:
var selectedRow = dataGridView1.SelectedRows[0];
var cellValue= selectedRow.Cells["RowName"].FormattedValue;

var collection = (DataView) dataGridView1.DataSource;
collection.Sort = "RowName";

var rowIndex = collection.Find(cellValue);
collection.Delete(rowIndex);

Here I used
SelectedRows[0]
since in my case multiple selection is turned off.

So 6 lines of code just to remove 1 row from DataGridView.... Maybe is there more elegant way to do that?

Комментариев нет:

Отправить комментарий