0

I'm trying to get the value of a cell in a DataGridView row using the source query column name. The DataGridView is populated from a BindingSource (as in its DataSource property is set to a BindingSource.)

var obj = dataGridView1.CurrentRow.DataBoundItem;

var item = (DataRow)obj;

On the second line I get an InvalidCastException:

Unable to cast object of type 'System.Data.DataRowView' to type 'System.Data.DataRow'.
cja
  • 9,512
  • 21
  • 75
  • 129
  • which event are you using to fire above code? – Zaki Mar 06 '13 at 12:18
  • Menu item click. I want to select the row then select a menu item and do something using the row data. – cja Mar 06 '13 at 12:23
  • see if this helps: http://stackoverflow.com/questions/3035144/right-click-to-select-a-row-in-a-datagridview-and-show-a-menu-to-delete-it – Zaki Mar 06 '13 at 12:29
  • No, I can get the row - that's just dataGridView1.CurrentRow – cja Mar 06 '13 at 12:32

1 Answers1

2

I guess your datasource is a DataTable. In that case the type of the DataBoundItem is DataRowView instead of DataRow. This based on the fact that DataGridView uses the default view of the DataTable. If you want to access the DataRow you need this:

        var obj = dataGridView1.CurrentRow.DataBoundItem;

        if (obj != null)
        {
            var item = ((DataRowView)obj).Row;
        }

Ps: I always avoid explicit cast of an object that in theory can be null.

Laszlo Boke
  • 1,319
  • 1
  • 10
  • 22