2010-10-12 148 views
52

我有一個DataGrid,綁定到數據庫表,我需要獲取DataGrid中選定行的內容,例如我想在MessageBox中顯示選定行的內容。獲取DataGrid中選定的行項WPF

DataGrid例子:

enter image description here

所以,如果我選擇第二行,我MessageBox必須證明是這樣的:646 Jim Biology

回答

109

您可以使用SelectedItem屬性來獲取當前選定的對象,然後您可以將其轉換爲正確的類型。舉例來說,如果你的DataGrid綁定到客戶對象的集合,你可以這樣做:

Customer customer = (Customer)myDataGrid.SelectedItem; 

或者你可以綁定的SelectedItem到源類或視圖模型。

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

謝謝,第一個很棒! – 2010-10-12 10:49:10

+2

謝謝,第二個也很棒! :) – Sam 2010-11-25 10:09:52

+1

第二個正是我所期待的。謝謝! – James 2014-09-11 17:44:21

15

如果您使用的是MVVM模式,則可以將虛擬機的SelectedRecord屬性與DataGrid的SelectedItem綁定,這樣您的虛擬機中始終有SelectedValue。 否則,您應該使用DataGrid的SelectedIndex屬性。

+0

我不使用MVVM,我只是用WPF/C#/開始。淨。 如果我編寫«ContentDataGrid.SelectedIndex»,我得到DataGrid中所選行的索引,而且我不需要索引,而是真正的值,比如«646 Jim Biology»。那我怎麼能得到它? – 2010-10-12 10:34:18

+0

您應該考慮使用綁定對象,以便可以綁定數據網格的SelectedItem屬性。在你的情況下,你應該嘗試導航到Datagrid屬性,以確定它是否存儲選定的項目屬性。 – ema 2010-10-12 11:24:06

+0

+1。那第一句話恰恰是*我正在尋找的東西! – TarkaDaal 2012-07-03 08:23:20

12
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 { } 
} 
+1

真的很好的解決方案!非常感謝你! – Mafii 2016-07-14 08:43:39

2

嗯,我會把這是對我工作的罰款類似的解決方案。

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

,如果我選擇第二行 -

Dim jason As DataRowView 


    jason = dg1.SelectedItem 

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

noteText將是646.這是VB,但你得到它。

1
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

你能解釋你的代碼嗎? – Rico 2014-04-03 17:54:49

2

這是本DataGrid的DG和項目類很簡單的DataGrid和listblock1填充是一個基本的框架。

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; } 
    } 
1

後,我試圖法拉的答案,但它並沒有在我的項目上工作剛剛發現這一點。只需從Data Sources窗口中拖動該列,然後拖放到Label或TextBox。

1

使用你的模型類來獲得從數據網格選擇像行值,

 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

你還可以:

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