小编典典

DataGrid获取选定行的列值

c#

我正在尝试获取DataGrid中选定行的每一列的值。这就是我所拥有的:

private void dataGrid1_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
    DataGrid dg = sender as DataGrid;
    Console.WriteLine(dg.SelectedCells[0].ToString());
}

但这是行不通的。如果我这样做,SelectedCells.Count那么我将获得正确的列数,但似乎无法实际获得所选行中这些列的值。我已经尝试了好久没有运气了!这是我的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的教程和帮助,但是我没有使用它。


阅读 432

收藏
2020-05-19

共1个答案

小编典典

更新

要获取选定的行,请尝试:

IList rows = dg.SelectedItems;

然后,您应该能够从行项目中获取列值。

要么

DataRowView row = (DataRowView)dg.SelectedItems[0];

然后:

row["ColumnName"];
2020-05-19