DataGrid 获取选定行的列值 [英] DataGrid get selected rows' column values
问题描述
我正在尝试获取 DataGrid 中选定行的每一列的值.这就是我所拥有的:
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());
}
但这行不通.如果我执行 SelectedCells.Count
然后我得到正确的列数,但我似乎无法实际获得所选行中这些列的值.我已经尝试了很长一段时间没有运气!这是我的 XAML:
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>
理想情况下,我希望通过执行诸如 rowData.UserID
之类的操作来访问数据,但我似乎无法解决.有很多关于使用 DataGridView 的教程和帮助,但我没有使用这个.
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.
推荐答案
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.
或
DataRowView row = (DataRowView)dg.SelectedItems[0];
那么:
row["ColumnName"];
这篇关于DataGrid 获取选定行的列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!