在 DataGrid WPF 中获取选定的行项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3913580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get selected row item in DataGrid WPF
提问by Mike B.
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.
我有一个DataGrid
,绑定到数据库表,我需要获取所选行的内容DataGrid
,例如,我想显示在MessageBox
所选行的内容中。
Example of DataGrid
:
示例DataGrid
:
So, if I select the second row, my MessageBox
has to show something like: 646 Jim Biology.
因此,如果我选择第二行,MessageBox
则必须显示如下内容:646 Jim Biology。
回答by Alex McBride
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:
您可以使用该SelectedItem
属性来获取当前选定的对象,然后您可以将其转换为正确的类型。例如,如果您DataGrid
绑定到一组Customer
对象,您可以这样做:
Customer customer = (Customer)myDataGrid.SelectedItem;
Alternatively you can bind SelectedItem
to your source class or ViewModel
.
或者,您可以绑定SelectedItem
到源类或ViewModel
.
<Grid DataContext="MyViewModel">
<DataGrid ItemsSource="{Binding Path=Customers}"
SelectedItem="{Binding Path=SelectedCustomer, Mode=TwoWay}"/>
</Grid>
回答by ema
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.
如果您使用的是 MVVM 模式,则可以将SelectedRecord
VM的属性与SelectedItem
DataGrid的属性绑定,这样SelectedValue
您的 VM 中就会始终拥有该属性。否则,您应该使用SelectedIndex
DataGrid的属性。
回答by Bahaa Salaheldin
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 { }
}
回答by Ali Zain
This is pretty simple in this DataGrid dg and item class is populated in datagrid and listblock1 is a basic frame.
这在这个 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; }
}
回答by Zeroox
You can also:
你也可以:
DataRowView row = dataGrid.SelectedItem as DataRowView;
MessageBox.Show(row.Row.ItemArray[1].ToString());
回答by Developer
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)
{
}
}
回答by f123
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.
在我尝试了 Fara 的答案后才发现了这个,但它对我的项目不起作用。只需将列从数据源窗口拖放到标签或文本框。
回答by Vijay Chauhan
use your Model class to get row values selected from datagrid like,
使用您的 Model 类获取从数据网格中选择的行值,例如,
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);
}
}
回答by Mwspencer
@Krytox answer with MVVM
@Krytox 回答 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
}
}
回答by Adnan Dean Taj
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
{
}
}
}
}
}