简体   繁体   English

如何从DataGrid中的选定行获取值?

[英]How to get values from selected row in DataGrid?

All I found is about DataGridView and have tried some event handlers and I'm stuck now. 我发现的所有内容都是关于DataGridView ,并尝试了一些事件处理程序,现在我陷入了困境。

Assuming I have DataGrid like below : 假设我有如下的DataGrid:

DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Code", typeof(String));
dt.Columns.Add("Name", typeof(String));
gridData.DataSource = dt;

How I capture onClick event with SelectedRows["ID"] 我如何使用SelectedRows["ID"]捕获onClick事件

This solution works for DataGridView but not with DataGrid. 解决方案适用于DataGridView但不适用于DataGrid。

You can use the property SelectedCells of that DataGrid. 您可以使用该DataGrid的属性SelectedCells That property returns to you an collection of current selected cells and you can iterate over that collection using a foreach loop 该属性返回给您当前选定单元格的集合,您可以使用foreach循环遍历该集合

Supposing that you want to get the values as strings, this code can be usefull: 假设您希望以字符串形式获取值,则此代码可能会有用:

// This is the list where the values will be stored. Now it's empty.
List<string> values = new List<string>();

// Whit this 'foreach' we iterate over 'gridData' selected cells.
foreach (DataGridCellInfo x in gridData.SelectedCells)
{
    // With this line we're storing the value of the cells as strings
    // in the previous list.
    values.Add(x.Item.ToString());
}

Then you can later make use of the stored values at your onClick() method. 然后,您可以稍后在onClick()方法中使用存储的值。

You can see the following Microsoft MSDN site: 您可以看到以下Microsoft MSDN网站:

DataGrid.SelectedCells Property DataGrid.SelectedCells属性

DataGridCellInfo Structure DataGridCellInfo结构

DataGridCellInfo.Item Property DataGridCellInfo.Item属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM