2

I've the following problem: I have a list "lst" of "Person" objects, and I put them in a DataGridView using a Dataview object ( I need it for filters )

        DataTable dt = Request.ListToDataTable(lst);
        dw = new DataView(dt);
        dw.Sort = "age ASC";
        dataGridView1.DataSource = dw;

When I click a button, I need to get the value of a field of the Person class that I put in a hidden column, relative to the selected row. To do that, I use :

        Person val = dataGridView1.SelectedRows[0].DataBoundItem as Person;
        Debug.WriteLine(val.id);

but when I run the program, the result is a crash, probably because the bound item is not a Person object but a DataTable element. Can somebody point me out how can I get that element? If the colum wasn't hidden it would have been easy, but this way I can't figure out how to obtain it! Thanks to everybody

Brian Rasmussen
  • 114,645
  • 34
  • 221
  • 317
kaharas
  • 597
  • 2
  • 17
  • 39
  • do lst.Sort(); dataGridView1.DataSource = lst; instead of current code. – Saeed Amiri Dec 28 '10 at 10:23
  • I need DataView to easily add and remove filters to the datagrid elements – kaharas Dec 28 '10 at 10:30
  • Where does `Request.ListToDataTable()` come from? Anyway, that seems to be where your Person objects are converted to DataRows. You can't cast back. – H H Dec 28 '10 at 10:33
  • ListToDataTable is the function shown here : http://stackoverflow.com/questions/564366/generic-list-to-datatable . Even if i can't cast back, can i look at the correct datatable row ? in there the column i'm interested in is included... – kaharas Dec 28 '10 at 10:36

2 Answers2

4

You will need something like:

var row = dataGridView1.SelectedRows[0].DataBoundItem as DataRow;
var val = row[X] as MyType;

Second attempt:

var drv = dataGridView1.SelectedRows[0].DataBoundItem as DataRowView;
var row = drv.Row as DataRow;
var val = row[X] as MyType;
H H
  • 263,252
  • 30
  • 330
  • 514
4

That is becuase , you are binding DataView to the DataGridView so the item collection will be of type DataRowView , to get it correctly .

DataRowView drv =   dataGridView1.SelectedRows[0].DataBoundItem as DataRowView ;

Now get the associated Row 

if(drv != null)
  {
    DataRow row = drv.Row;

   // Now get the respective column value say PersonId and assuming PersonId is a column in the bounded DataView

    if(row!=null)
      {
        var personId = row["PersonId"];
      }
  }
TalentTuner
  • 17,262
  • 5
  • 38
  • 63