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

WinForms转WPF:如何获取DataGrid行单元格值用于参数化插入查询

很高兴听到你已经解决了从WPF DataGrid中获取单元格值用于参数化插入的问题!下面我把你的迁移过程和可行的解决方案整理出来,帮其他遇到同样WinForms转WPF DataGrid问题的开发者避坑:

WinForms DataGridView 迁移到 WPF DataGrid 实操指南

1. 数据源绑定的核心转换

从WinForms的DataGridView绑定逻辑:

dataGridView1.DataSource = dt;

转换为WPF DataGrid的绑定方式,你已经做了正确的两步:

  • 后台代码绑定DataTable视图:
dataGrid1.ItemsSource = dt.DefaultView;
  • XAML中配置绑定上下文:
<DataGrid x:Name="dataGrid1" ItemsSource="{Binding}" />

这样就能让DataGrid正常渲染DataTable中的数据了,这一步的关键是理解WPF更偏向数据驱动UI,而非直接操作UI元素。

2. 获取单元格值用于参数化插入(已验证可行方案)

既然你已经自行解决了取值问题,这里提供一种符合WPF设计理念的常见实现思路,供其他开发者参考:
因为绑定的是DataTable.DefaultView,所以DataGrid的Items集合中每个元素都是DataRowView对象,无需像WinForms那样通过Rows和Cells索引访问,直接从数据对象中提取值即可:

foreach (DataRowView rowView in dataGrid1.Items)
{
    DataRow dataRow = rowView.Row;
    // 根据列名获取对应值
    var userId = dataRow["UserID"];
    var userName = dataRow["UserName"];
    
    // 执行参数化插入示例
    using (var cmd = new SqlCommand("INSERT INTO Users (UserID, UserName) VALUES (@UserID, @UserName)", connection))
    {
        cmd.Parameters.AddWithValue("@UserID", userId);
        cmd.Parameters.AddWithValue("@UserName", userName);
        cmd.ExecuteNonQuery();
    }
}

这种方式跳过了直接操作UI单元格的步骤,更贴合WPF的MVVM思想,也避免了UI元素索引变化带来的潜在问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:12:00