[c#] DataGrid get selected rows' column values

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.

This question is related to c# .net wpf datagrid

The answer is


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"];

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();
}

If you are using an SQL query to populate your DataGrid you can do this :

Datagrid fill

Private Sub UserControl_Loaded(sender As Object, e As RoutedEventArgs)
        Dim cmd As SqlCommand
        Dim da As SqlDataAdapter
        Dim dt As DataTable

        cmd = New SqlCommand With {
            .CommandText = "SELECT * FROM temp_rech_dossier_route",
            .Connection = connSQLServer
        }
        da = New SqlDataAdapter(cmd)
        dt = New DataTable("RECH")
        da.Fill(dt)
        DataGridRech.ItemsSource = dt.DefaultView
End Sub

Value diplay

    Private Sub DataGridRech_SelectionChanged(sender As Object, e As SelectionChangedEventArgs) Handles DataGridRech.SelectionChanged
        Dim val As DataRowView
        val = CType(DataGridRech.SelectedItem, DataRowView)
        Console.WriteLine(val.Row.Item("num_dos"))
    End Sub

I know it's in VB.Net but it can be translated into C#. I put this solution here, it might be useful for someone.


I used a similar way to solve this problem using the animescm sugestion, indeed we can obtain the specific cells values from a group of selected cells using an auxiliar list:

private void dataGridCase_SelectionChanged(object sender, SelectedCellsChangedEventArgs e)
    {
        foreach (var item in e.AddedCells)
        {
            var col = item.Column as DataGridColumn;
            var fc = col.GetCellContent(item.Item);
            lstTxns.Items.Add((fc as TextBlock).Text);
        }
    }

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. :)


Solution based on Tonys answer:

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

An easy way that works:

private void dataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
    foreach (var item in e.AddedCells)
    {
        var col = item.Column as DataGridColumn;
        var fc = col.GetCellContent(item.Item);

        if (fc is CheckBox)
        {
            Debug.WriteLine("Values" + (fc as CheckBox).IsChecked);
        }
        else if(fc is TextBlock)
        {
            Debug.WriteLine("Values" + (fc as TextBlock).Text);
        }
        //// Like this for all available types of cells
    }
}

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.


After hours of finding ways on how to get the data from the row selected on a WPF DataGrid Control, as I was using MongoDB. I found this post and used Tony's answer. I revised the code to be relevant to my project. Maybe someone can use this to get an idea.

private void selectionChanged(object sender, SelectionChangedEventArgs e)
    {
        facultyData row = (facultyData)facultyDataGrid.SelectedItem;
        facultyID_Textbox.Text = row.facultyID;
        lastName_TextBox.Text = row.lastName;
        firstName_TextBox.Text = row.firstName;
        middleName_TextBox.Text = row.middleName;
        age_TextBox.Text = row.age.ToString();
    }

}

class facultyData
{
    public ObjectId _id { get; set; }
    public string facultyID { get; set; }
    public string acadYear { get; set; }
    public string program { get; set; }   
}

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to wpf

Error: the entity type requires a primary key Reportviewer tool missing in visual studio 2017 RC Pass command parameter to method in ViewModel in WPF? Calling async method on button click Setting DataContext in XAML in WPF How to resolve this System.IO.FileNotFoundException System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll? Binding an Image in WPF MVVM How to bind DataTable to Datagrid Setting cursor at the end of any text of a textbox

Examples related to datagrid

How to bind DataTable to Datagrid WPF Datagrid Get Selected Cell Value Wpf DataGrid Add new row How to clear a data grid view Adding values to specific DataTable cells Accessing UI (Main) Thread safely in WPF Date formatting in WPF datagrid How to hide column of DataGridView when using custom DataSource? How can I disable editing cells in a WPF Datagrid? Datagrid binding in WPF