Get selected row item in DataGrid WPF

WpfDatagridSelecteditem

Wpf Problem Overview


I have a DataGrid, bound to Database table, I need to get the content of selected row in DataGrid, for example, I want to show in MessageBox content of selected row.

Example of DataGrid:

enter image description here

So, if I select the second row, my MessageBox has to show something like: 646 Jim Biology.

Wpf Solutions


Solution 1 - Wpf

You can use the SelectedItem property to get the currently selected object, which you can then cast into the correct type. For instance, if your DataGrid is bound to a collection of Customer objects you could do this:

Customer customer = (Customer)myDataGrid.SelectedItem;

Alternatively you can bind SelectedItem to your source class or ViewModel.

<Grid DataContext="MyViewModel">
	<DataGrid ItemsSource="{Binding Path=Customers}"
			  SelectedItem="{Binding Path=SelectedCustomer, Mode=TwoWay}"/>
</Grid>

Solution 2 - Wpf

If you're using the MVVM pattern you can bind a SelectedRecord property of your VM with SelectedItem of the DataGrid, this way you always have the SelectedValue in you VM. Otherwise you should use the SelectedIndex property of the DataGrid.

Solution 3 - Wpf

public IEnumerable<DataGridRow> GetDataGridRows(DataGrid grid)
{
    var itemsSource = grid.ItemsSource as IEnumerable;
    if (null == itemsSource) yield return null;
    foreach (var item in itemsSource)
    {
        var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
        if (null != row) yield return row;
    }
}

private void DataGrid_Details_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    try
    {           
        var row_list = GetDataGridRows(DataGrid_Details);
        foreach (DataGridRow single_row in row_lis)
        {
            if (single_row.IsSelected == true)
            {
                MessageBox.Show("the row no."+single_row .GetIndex ().ToString ()+ " is selected!");
            }
        }

    }
    catch { }
}

Solution 4 - Wpf

This is pretty simple in this DataGrid dg and item class is populated in datagrid and listblock1 is a basic frame.

private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        try
        {
            var row_list = (Item)dg.SelectedItem;
            listblock1.Content = "You Selected: " + row_list.FirstName + " " + row_list.LastName;
        }
        catch { }

    }
    public class Item
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

Solution 5 - Wpf

You can also:

DataRowView row = dataGrid.SelectedItem as DataRowView;
MessageBox.Show(row.Row.ItemArray[1].ToString());

Solution 6 - Wpf

Well I will put similar solution that is working fine for me.

 private void DataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (DataGrid1.SelectedItem != null)
                {
                    if (DataGrid1.SelectedItem is YouCustomClass)
                    {
                        var row = (YouCustomClass)DataGrid1.SelectedItem;

                        if (row != null)
                        {
                            // Do something...

                            //  ButtonSaveData.IsEnabled = true;

                            //  LabelName.Content = row.Name;
                             
                        }
                    }
                }
            }
            catch (Exception)
            {
            }
        }

Solution 7 - Wpf

@Krytox answer with MVVM

    <DataGrid 
        Grid.Column="1" 
        Grid.Row="1"
        Margin="10" Grid.RowSpan="2"
        ItemsSource="{Binding Data_Table}"
        SelectedItem="{Binding Select_Request, Mode=TwoWay}" SelectionChanged="DataGrid_SelectionChanged"/>//The binding



    #region View Model
    private DataRowView select_request;
    public DataRowView Select_Request
    {
        get { return select_request; }
        set
        {
            select_request = value;
            OnPropertyChanged("Select_Request"); //INotifyPropertyChange
            OnSelect_RequestChange();//do stuff
        }
     }

Solution 8 - Wpf

private void Fetching_Record_Grid_MouseDoubleClick_1(object sender, MouseButtonEventArgs e)
{
    IInputElement element = e.MouseDevice.DirectlyOver;
    if (element != null && element is FrameworkElement)
    {
        if (((FrameworkElement)element).Parent is DataGridCell)
        {
            var grid = sender as DataGrid;
            if (grid != null && grid.SelectedItems != null && grid.SelectedItems.Count == 1)
            {
                //var rowView = grid.SelectedItem as DataRowView;
                try
                {
                    Station station = (Station)grid.SelectedItem;
                    id_txt.Text =  station.StationID.Trim() ;
                    description_txt.Text =  station.Description.Trim();
                }
                catch
                {

                }
            }
        }
    }
}

Solution 9 - Wpf

Just discovered this one after i tried Fara's answer but it didn't work on my project. Just drag the column from the Data Sources window, and drop to the Label or TextBox.

Solution 10 - Wpf

use your Model class to get row values selected from datagrid like,

        XDocument xmlDoc = XDocument.Load(filepath);

        if (tablet_DG.SelectedValue == null)
        {
            MessageBox.Show("select any record from list..!", "select atleast one record", MessageBoxButton.OKCancel, MessageBoxImage.Warning);
        }
        else
        {
            try
            {
                string tabletID = "";

                 /*here i have used my model class named as TabletMode*/

                var row_list = (TabletModel)tablet_DG.SelectedItem; 
                 tabletID= row_list.TabletID;

                var items = from item in xmlDoc.Descendants("Tablet")
                            where item.Element("TabletID").Value == tabletID
                            select item;

                foreach (var item in items)
                {
                    item.SetElementValue("Instance",row_list.Instance);
                    item.SetElementValue("Database",row_list.Database);
                }

                xmlDoc.Save(filepath);
                MessageBox.Show("Details Updated..!"
                + Environment.NewLine + "TabletId: " +row_list.TabletID + Environment.NewLine
                + "Instance:" + row_list.Instance + Environment.NewLine + "Database:" + row_list.Database, "", MessageBoxButton.YesNoCancel, MessageBoxImage.Information);
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.StackTrace);
            }
        }

Solution 11 - Wpf

if I select the second row -

 Dim jason As DataRowView


    jason = dg1.SelectedItem

    noteText.Text = jason.Item(0).ToString()

noteText will be 646. This is VB, but you get it.

Solution 12 - Wpf

There are a lot of answers here that probably work in a specific context, but I was simply trying to get the text value of the first cell in a selected row. While the accepted answer here was the closest for me, it still required creating a type and casting the row into that type. I was looking for a simpler solution, and this is what I came up with:

MessageBox.Show(((DataRowView)DataGrid.SelectedItem).Row[0].ToString());

This gives me the first column in the selected row. Hopefully this helps someone else.

Solution 13 - Wpf

I got something like this:

private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e) {

	DataGrid dg = (DataGrid)sender;

	DataRowView selectedRow = dg.SelectedItem as DataRowView;

	if(selectedRow != null) {
		txtXXX.Text = selectedRow["xxx"].ToString();
		txtYYY.Text = selectedRow["yyy"].ToString();
		txtZZZ.Text = selectedRow["zzz"].ToString();
	}

}

Solution 14 - Wpf

Your front code:

  • set your model namespace xmlns:viewModel="clr-namespace:CPL3_workstation.MVVM.ModelViews.Tables"
  • set xmlns:d="http://schemas.microsoft.com/expression/blend/2008", because d:DataContext="{d:DesignInstance...}
<DataGrid d:DataContext="{d:DesignInstance viewModel:TestViewModel, IsDesignTimeCreatable=True}"
          ItemsSource="{Binding Rows}"
          SelectedItem="{Binding Selector}">
    <DataGrid.Columns>
        <DataGridTextColumn
            Binding="{Binding Content1}"
            Header="Столбец 1" />
        <DataGridTextColumn
            Binding="{Binding Content2}"
            Header="Столбец 2" />
        <DataGridTextColumn
            Binding="{Binding Content3}"
            Header="Столбец 3" />
    </DataGrid.Columns>
</DataGrid>

Your ViewModel and the Model below:

namespace CPL3_workstation.MVVM.ModelViews.Tables
{
	public class TestViewModel
	{
		public IEnumerable<TestModel> Rows { get; set; }

		public TestModel Selector
		{
			get => selector;
			set => selector = value;
		}

		private TestModel selector;

		public TestViewModel()
		{
			Rows = new List<TestModel>
			{
				new TestModel{ Content1 = "one", Content2 = "two", Content3 = "three" },
				new TestModel{ Content1 = "one", Content2 = "two", Content3 = "three" },
				new TestModel{ Content1 = "one", Content2 = "two", Content3 = "three" },
				new TestModel{ Content1 = "one", Content2 = "two", Content3 = "three" }
			};
		}
	}

	public class TestModel
	{
		public string Content1 { get; set; }
		public string Content2 { get; set; }
		public string Content3 { get; set; }
	}
}

As you can see, the SelectedItem has a binding to the Selector property of the type of your model.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMikeView Question on Stackoverflow
Solution 1 - WpfAlex McBrideView Answer on Stackoverflow
Solution 2 - WpfemaView Answer on Stackoverflow
Solution 3 - WpfBahaa SalaheldinView Answer on Stackoverflow
Solution 4 - WpfAli ZainView Answer on Stackoverflow
Solution 5 - WpfZerooxView Answer on Stackoverflow
Solution 6 - WpfNoWarView Answer on Stackoverflow
Solution 7 - WpfMwspencerView Answer on Stackoverflow
Solution 8 - WpfAdnan Dean TajView Answer on Stackoverflow
Solution 9 - Wpff123View Answer on Stackoverflow
Solution 10 - WpfVijay ChauhanView Answer on Stackoverflow
Solution 11 - WpfdeskplaceView Answer on Stackoverflow
Solution 12 - WpfnherrmannView Answer on Stackoverflow
Solution 13 - WpfGuest28512View Answer on Stackoverflow
Solution 14 - WpfRashid HasanovView Answer on Stackoverflow