【问题标题】:How to get values from selected row in DataGrid?如何从 DataGrid 中的选定行中获取值?
【发布时间】:2018-05-07 18:32:55
【问题描述】:

我找到的都是关于 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;

我如何使用SelectedRows["ID"] 捕获onClick 事件

这个solution 适用于DataGridView,但不适用于DataGrid。

【问题讨论】:

  • 您使用的是哪个 .NET 版本?
  • @CryogenicNeo:.NET Framework 4.6.1
  • SelectedCells 属性在此版本的 .NET 中可用,它必须是可能的。
  • @CryogenicNeo:遗憾的是不适用于 Windows 窗体。是的 WPF。
  • 来自MSDN on the DataGrid control "DataGridView 控件替换了 DataGrid 控件并向其添加了功能;但是,如果您愿意,可以保留 DataGrid 控件以供向后兼容和将来使用。"我认为您最好的选择是改用 DataGridView。

标签: c# winforms datagrid


【解决方案1】:

您可以使用该 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

【讨论】:

  • SelectedCells 仅在 DataGridView 中可用,在 DataGrid 中不可用
  • 微软 MSDN 显示它有:DataGrid.SelectedCells Property
  • 感谢cryo,但是现在当我添加程序集时这变得很奇怪,它返回错误'DataGrid' is an ambiguous reference between 'System.Windows.Controls.DataGrid' and 'System.Windows.Forms.DataGrid' ...我会看看这个并尽快更新它。谢谢。
  • DataGrid必须在两个程序集中,您必须在指定类时在DataGrid声明处添加System.Windows.Forms.System.Windows.Controls.来指定程序集。
  • 好的,这个 SelectedCells 属性适用于 WPF 而不是 Windows 窗体。
猜你喜欢
  • 2012-11-11
  • 2016-10-13
  • 1970-01-01
  • 1970-01-01
  • 2017-11-22
  • 2017-08-18
  • 2011-07-04
  • 2016-08-11
  • 1970-01-01
相关资源
最近更新 更多