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

时间:2018-05-07 18:32:55

标签: c# winforms datagrid

我找到的只是关于DataGridView并尝试了一些事件处理程序,现在我已经陷入困境。

假设我有如下的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;

我如何使用onClick

捕获SelectedRows["ID"]个事件

solution适用于DataGridView,但适用于DataGrid。

1 个答案:

答案 0 :(得分:0)

您可以使用该DataGrid的属性SelectedCells。该属性会返回当前所选单元格的集合,您可以使用foreach循环遍历该集合

假设您希望将值作为字符串获取,则此代码可能非常有用:

// 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());
}

然后,您可以稍后使用onClick()方法中的存储值。

  

您可以看到以下Microsoft MSDN站点:

     

DataGrid.SelectedCells Property

     

DataGridCellInfo Structure

     

DataGridCellInfo.Item Property