DataGrid get selected rows' column values

176,919

Solution 1

UPDATED

To get the selected rows try:

IList rows = dg.SelectedItems;

You should then be able to get to the column value from a row item.

OR

DataRowView row = (DataRowView)dg.SelectedItems[0];

Then:

row["ColumnName"];

Solution 2

Solution based on Tonys answer:

        DataGrid dg = sender as DataGrid;
        User row = (User)dg.SelectedItems[0];
        Console.WriteLine(row.UserID);

Solution 3

I did something similar but I use binding to get the selected item :

<DataGrid Grid.Row="1" AutoGenerateColumns="False" Name="dataGrid"
          IsReadOnly="True" SelectionMode="Single"
          ItemsSource="{Binding ObservableContactList}" 
          SelectedItem="{Binding SelectedContact}">
  <DataGrid.Columns>
    <DataGridTextColumn Binding="{Binding Path=Name}" Header="Name"/>
    <DataGridTextColumn Binding="{Binding Path=FamilyName}" Header="FamilyName"/>
    <DataGridTextColumn Binding="{Binding Path=Age}" Header="Age"/>
    <DataGridTextColumn Binding="{Binding Path=Relation}" Header="Relation"/>
    <DataGridTextColumn Binding="{Binding Path=Phone.Display}" Header="Phone"/>
    <DataGridTextColumn Binding="{Binding Path=Address.Display}" Header="Addr"/>
    <DataGridTextColumn Binding="{Binding Path=Mail}" Header="E-mail"/>
  </DataGrid.Columns>
</DataGrid>

So I can access my SelectedContact.Name in my ViewModel.

Solution 4

DataGrid get selected rows' column values it can be access by below code. Here grid1 is name of Gride.

private void Edit_Click(object sender, RoutedEventArgs e)
{
    DataRowView rowview = grid1.SelectedItem as DataRowView;
    string id = rowview.Row[0].ToString();
}

Solution 5

I believe the reason there's no straightforward property to access the selected row of a WPF DataGrid is because a DataGrid's selection mode can be set to either the row-level or the cell-level. Therefore, the selection-related properties and events are all written against cell-level selection - you'll always have selected cells regardless of the grid's selection mode, but you aren't guaranteed to have a selected row.

I don't know precisely what you're trying to achieve by handling the CellEditEnding event, but to get the values of all selected cells when you select a row, take a look at handling the SelectedCellsChanged event, instead. Especially note the remarks in that article:

You can handle the SelectedCellsChanged event to be notified when the collection of selected cells is changed. If the selection includes full rows, the Selector.SelectionChanged event is also raised.

You can retrieve the AddedCells and RemovedCells from the SelectedCellsChangedEventArgs in the event handler.

Hope that helps put you on the right track. :)

Share:
176,919
Prisoner
Author by

Prisoner

no, your about me is currently blank.

Updated on January 14, 2021

Comments

  • Prisoner
    Prisoner over 3 years

    I'm trying to get the values of each column of a selected row in a DataGrid. This is what I have:

    private void dataGrid1_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
    {
        DataGrid dg = sender as DataGrid;
        Console.WriteLine(dg.SelectedCells[0].ToString());
    }
    

    But this does not work. If I do a SelectedCells.Count then I get the correct number of columns but I cannot seem to actually get the values of these columns in the selected row. I've tried for quite a while with no luck! Here is my XAML:

    <Grid>
        <DataGrid CanUserAddRows="True" AutoGenerateColumns="False" Height="200" HorizontalAlignment="Stretch" Margin="12,12,79,0" Name="dataGrid1" VerticalAlignment="Top" Width="389" DataContext="{Binding}" CanUserResizeColumns="False" CanUserResizeRows="False" HorizontalContentAlignment="Stretch" PreviewMouseDoubleClick="dataGrid1_PreviewMouseDoubleClick" CellEditEnding="dataGrid1_CellEditEnding">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding  Path=UserID}"
                                    Header="User ID" Width="SizeToHeader" />
                <DataGridTextColumn Binding="{Binding  Path=UserName}"
                                    Header="User ID" Width="SizeToHeader" />
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
    

    I would ideally like to access the data through doing something like rowData.UserID but I cannot seem to work it out. There are lots of tutorials and help for using DataGridView but I'm not using this.

  • Prisoner
    Prisoner about 13 years
    I should have mentioned this is WPF and there doesn't seem to be SelectedRows/SelectedRow
  • Prisoner
    Prisoner about 13 years
    The second option gives me: Unable to cast object of type 'iAdvert_Desktop.User' to type 'System.Data.DataRowView' and I cannot get the first option to work either :/. I'm pretty new to C#.
  • Prisoner
    Prisoner about 13 years
    Well, the idea of this piece of code is to allow me to: Click to edit a username, then when ending the edit I want to save the value based on the UserID of the user which is ReadOnly. So I need to get all the cells for a row (well, only UserID and UserName in this instance).
  • Tony Abrams
    Tony Abrams about 13 years
    You can change the DataRowView to be User. See if that does it. I was unsure what the type was of your items.
  • ouflak
    ouflak over 10 years
    I guess this is fine if you have a CheckBox in every one of your cells. Ofcourse in the infinite number of situation where don't...
  • Arrie
    Arrie about 9 years
    old question this , but i changed SelectedItems[0] to SelectedItem... but this helped me alot! :) upvote!
  • MindRoasterMir
    MindRoasterMir over 5 years
    Rather than giving row["columnName"] you can also give row[0] and so one. Thanks
  • Jeff
    Jeff over 4 years
    You can, but I don't recommend it. When someone comes along later and adds a column the indexes break and you're now referencing a different field. That may break in unique, hidden and special ways... At least with a column name if someone changes the name of the column or removes it the app will at least error early and obviously. Upvote for the comment though because it is an option.
  • Admin
    Admin over 4 years
    What is lstTxns.Items.Add
  • nam
    nam over 3 years
    @TonyAbrams To me DataRowView row = (DataRowView)dg.SelectedItems[0]; returns row as null. But this suggestion works. I've added a button in each row, and I'm using the code in button click event of a row. But it still surprises me why your suggestion did not work while the other suggestion worked. I wonder what could be a reason?
  • DmVinny
    DmVinny about 3 years
    Probably the easiest way, you can also call it by column names as well string id = rowview.Row["Id"].ToString();