0

I have a DataGrid for search results, that I want the user to be able to click on a row, and it load that customer's details. The first index of the row (index position 0) has the ID in, so once I get the selected row it will be very simple, however, I'm having trouble extracting this information. Is there a way to do something like:

string ID = myGrid.selectedRow[0].ToString();

I already have the selectionChanged event programmed and triggering, I just can't seem to get the data out..

AllFallD0wn
  • 551
  • 7
  • 23

2 Answers2

2

I see the tag WPF, that means that you are using DataBinding, that means that you have a ModelView or at least Model. Having this architecture, especially in WPF, never and ever read the data from UI, read it from the bound data-model.

Robaticus
  • 22,857
  • 5
  • 54
  • 63
Tigran
  • 61,654
  • 8
  • 86
  • 123
  • So I should take the index of the selected row and use that to load the details? – AllFallD0wn Apr 17 '12 at 16:32
  • No, you should have in your ModelView an item with bool Selected property and check from it. – Tigran Apr 17 '12 at 16:35
  • or if you don't wan't to make a comples things have a look on this answers in SO: [Get selected row item in DataGrid WPF](http://stackoverflow.com/questions/3913580/get-selected-row-item-in-datagrid-wpf), or [WPF Datagrid set selected row](http://stackoverflow.com/questions/1976087/wpf-datagrid-set-selected-row) – Tigran Apr 17 '12 at 16:37
1

There is really a very simple way to do this using SelectedIndex.

int i = yourgrid.SelectedIndex;
DataRowView v = (DataRowView)yourgrid.Items[i];  // this give you access to the row
string s = (string)v[0];  // this gives you the value in column 0.

You can also do: string s = (string)v["columnname"];
this protects you from the user moving the column around

Bob
  • 21
  • 1