You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF中如何获取DataGrid选中项对应的DataTable行

如何从筛选后的DataGrid中获取选中项并导入到新DataTable?

我通过SQL查询填充了一个DataTable,并将其设置为DataGrid的ItemsSource。需要找到DataGrid中选中项对应的DataTable行,添加到新的DataTable中。原本想通过选中项的索引用datatable.rows[x]访问,但因为用户会对DataGrid进行文本筛选,所以得从筛选对应的DataView中查找数据。

实现代码

private void btnAddPart_Click(object sender, RoutedEventArgs e)
{
    var item = (DataRowView)dgParts.SelectedItem;
    if (item != null)
    {
        DataRow row = item.Row;
        dtDocParts.ImportRow(row);
    }

    dgDocParts.ItemsSource = dtDocParts.AsDataView();
}

重要说明

  • 筛选后的DataGrid选中项类型为DataRowView,直接强转即可获取对应视图对象,进而拿到原始的DataRow
  • 必须使用ImportRow方法来添加行,不能用Rows.Add——因为一行数据只能属于一个DataTable,使用Add会触发异常
  • 操作完成后,将新DataTable转为DataView,重新绑定到目标DataGrid的ItemsSource,确保界面同步更新

内容的提问来源于stack exchange,提问作者m4rs___

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 14:20:56