Get selected row in DataGrid WPF

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

DataGrid Example:

enter image description here

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

+58
wpf datagrid selecteditem
Oct 12 2018-10-10
source share
13 answers

You can use the SelectedItem property to get the currently selected object, which can then be converted to the correct type. For example, if your DataGrid is associated with a collection of Customer objects, you can 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> 
+124
Oct 12 '10 at 10:44
source share

If you use the MVVM pattern, you can bind the SelectedRecord property of your virtual machine using the SelectedItem DataGrid, so you always have a SelectedValue in your virtual machine. Otherwise, you should use the SelectedIndex DataGrid property.

+17
12 Oct '10 at 10:27
source share
 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 { } } 
+12
Apr 19 '11 at 10:01
source share

It's pretty simple in this DataGrid dg, and the item class is populated in the datagrid, and listblock1 is the base 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; } } 
+4
Oct 24 '14 at 21:34
source share

You also can:

 DataRowView row = dataGrid.SelectedItem as DataRowView; MessageBox.Show(row.Row.ItemArray[1].ToString()); 
+4
Dec 17 '17 at 18:41
source share

Ok, I will put a similar solution that works 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) { } } 
+2
Dec 21 '12 at 3:19
source share
 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 { } } } } } 
+1
Apr 03 '14 at 17:05
source share

Just opened it after I asked Fara to answer, but he did not work on my project. Just drag a column from the Data Sources window and go to Label or TextBox.

+1
Feb 25 '15 at 8:20
source share

use the Model class to get the values โ€‹โ€‹of the rows selected from the datagrid, e.g.

  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); } } 
+1
Jul 21 '15 at 6:50
source share

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 will get it.

0
Feb 15 '13 at 5:14
source share

@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 } } 
0
Apr 13 '18 at
source share

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

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

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

0
Feb 11 '19 at 16:57
source share

I can not comment directly, so I checked the answer and voted to show the idea

 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 { } } 

But what happens is that while I scroll, the selected line repeatedly shows up, I think due to the approach of ContainerFromItem .

Is it possible to change the background of a DataGrid programmatically, only in C # code?

I tried to play a little with the selected index, and it is not as simple as in WindowsForms . So, I tried to figure out how to perform the selection.

I use: DataTable in a DataObject which is the source of the dataObject.DataTable of the DataGrid elements is dataObject.DataTable . I know that I need to execute .Background = Brushes."DesiredColor" in a DataGridRow. But am not sure if there is any relation between DataGridRow. But am not sure if there is any relation between DataGridRow. But am not sure if there is any relation between DataGridRow. But am not sure if there is any relation between selected index/selected item/ DataGrid selected index/selected item/ SelectedItems' and the Background property.

0
Jun 04 '19 at 11:43 on
source share



All Articles