1

My dataGrid

As you can see in my DataGrid I have the Id in the first column, I would like to get that number. The data received can be made up of all of the data in that row as I can sub-string to contain only the data that I need.

I tried using SelectedItem but it brings up the object name and not the data itself.

string selectedInfo = dataGrid.SelectedItem.ToString();
thatguy
  • 21,059
  • 6
  • 30
  • 40
  • Check the default [ToString](https://learn.microsoft.com/en-us/dotnet/api/system.object.tostring?view=netcore-3.1) implementation, that states that it returns the type name of the object. You'll need to cast the `SelectedItem` to whatever object it is so you can access its properties – MindSwipe Aug 10 '20 at 07:29
  • You shouldn't operate with control for anything related to data. Look into MVVM, using it will make your code easier to read/maintain. Just [bind selected items](https://stackoverflow.com/q/9880589/1997232) and operate with data in view model. – Sinatr Aug 10 '20 at 07:32

2 Answers2

1

Doing this:

dataGrid.SelectedItem.ToString();

you get object type name.

To get selected item and Id:

var item = dataGrid.SelectedItem as YourObjectType; // gets object, not type name - cast is also needed

if (item != null)
{
    var id = item.Id;
} 
Roman
  • 11,966
  • 10
  • 38
  • 47
0

The usual approach to this is to bind the selecteditem of the datagrid to a property in a viewmodel which is of the same type as each row.

You can then reference that in the viewmodel and work with the Id.

In the view:

<DataGrid SelectedItem="{Binding SelectedThing}"

Thing would usually be whatever type each item is. This itself is usually a viewmodel.

In the viewmodel:

private Thing selectedThing;

public Thing SelectedThing
{
    get => selectedThing;
    set { SetProperty(ref selectedThing, value); }
}

Somewhere in that viewmodel where you need the id.

var id = selectedThing?.Id ?? -1;
Andy
  • 11,864
  • 2
  • 17
  • 20