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

C# WinForm选中DataGridView行后更新另一个DataGridView

实现WinForm双DataGridView关联展示的方案

没问题,刚接触编程遇到这种关联数据展示的需求太正常了,我一步步给你拆解怎么实现:

1. 绑定客户DataGridView的选中事件

首先你需要给客户DataGridView(假设命名为dgvCustomers)绑定选中变更事件,这样用户选中某一行时就能触发后续逻辑。

你可以直接在WinForm设计器里操作:

  • 选中dgvCustomers
  • 在右侧属性面板找到Events(闪电图标)
  • 找到SelectionChanged事件,双击它自动生成事件处理方法

或者手动在代码里添加绑定(比如在窗体的Load事件里):

dgvCustomers.SelectionChanged += dgvCustomers_SelectionChanged;

然后在事件处理方法里获取选中的客户ID,并触发联系人加载:

private void dgvCustomers_SelectionChanged(object sender, EventArgs e)
{
    // 先判断是否有有效选中行(避免用户点击空白区域报错)
    if (dgvCustomers.SelectedRows.Count > 0 && dgvCustomers.SelectedRows[0].Cells["CustomerId"].Value != DBNull.Value)
    {
        // 从选中行提取客户ID(这里假设你的客户表主键列名为CustomerId)
        int customerId = Convert.ToInt32(dgvCustomers.SelectedRows[0].Cells["CustomerId"].Value);
        
        // 调用加载联系人的方法
        LoadAssociatedContacts(customerId);
    }
    else
    {
        // 没有选中行时清空联系人表格
        dgvContacts.DataSource = null;
    }
}

2. 实现按客户ID加载联系人的方法

接下来写一个专门的方法,负责根据客户ID从数据库查询关联联系人,并绑定到第二个DataGridView(假设命名为dgvContacts)。这里一定要用参数化查询,避免SQL注入风险:

private void LoadAssociatedContacts(int customerId)
{
    // 替换成你的数据库连接字符串
    string connStr = "Server=你的服务器地址;Database=你的数据库名;User Id=账号;Password=密码;";
    // 查询SQL(假设联系人表通过CustomerId外键关联客户表)
    string query = "SELECT ContactId, ContactName, Phone, Email, Position FROM Contacts WHERE CustomerId = @CustomerId";

    try
    {
        using (SqlConnection conn = new SqlConnection(connStr))
        {
            using (SqlCommand cmd = new SqlCommand(query, conn))
            {
                // 添加参数,避免SQL注入
                cmd.Parameters.AddWithValue("@CustomerId", customerId);
                
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                DataTable contactTable = new DataTable();
                
                conn.Open();
                adapter.Fill(contactTable);
                conn.Close();
                
                // 将查询结果绑定到联系人DataGridView
                dgvContacts.DataSource = contactTable;
            }
        }
    }
    catch (Exception ex)
    {
        // 异常处理,给用户提示
        MessageBox.Show("加载联系人失败:" + ex.Message);
    }
}

3. 关键配置与优化建议

  • 设置DataGridView选中模式:确保dgvCustomers的SelectionMode属性设为FullRowSelect,这样用户点击整行都会触发选中(设计器里直接改,或者代码里:dgvCustomers.SelectionMode = DataGridViewSelectionMode.FullRowSelect;)
  • 使用BindingSource优化绑定:如果你的DataGridView是通过BindingSource绑定的,更新数据源时可以直接操作BindingSource,体验更流畅:
    // 先在窗体类里声明BindingSource
    private BindingSource contactBindingSource = new BindingSource();
    
    // 初始化时绑定
    dgvContacts.DataSource = contactBindingSource;
    
    // 加载联系人时更新
    contactBindingSource.DataSource = contactTable;
    
  • 空值判断:一定要处理单元格值为DBNull的情况,避免转换类型时抛出异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:31:55