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

如何将带外键关联的两张表绑定到两个dataGridView并实现联动

实现DataGridView联动筛选的解决方案

核心修改逻辑

你当前的代码将两张表分别存到了独立的DataSet中,无法利用内置的绑定关联机制,我们只需调整数据存储结构和绑定规则即可实现自动联动,无需额外编写事件处理代码:

  • 共用同一个DataSet存储Genre和Film两张表
  • 在DataSet内创建匹配外键约束的表间关系
  • 将Film对应的BindingSource绑定到Genre的BindingSource及表间关系上,自动完成筛选

修改后完整代码

// 把BindingSource提到类级别,避免生命周期问题
private BindingSource bindingSource1 = new BindingSource();
private BindingSource bindingSource2 = new BindingSource();

private void Form1_Load(object sender, EventArgs e)
{                         
    SqlConnection connectionDB = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\user\source\repos\DBWork\DBWork\Database1.mdf;Integrated Security=True");
    // 共用同一个DataSet存储两张表
    DataSet dataSet = new DataSet();
    try
    {
        connectionDB.Open();         
        SqlDataAdapter dataAdapter1 = new SqlDataAdapter("SELECT * FROM Genre", connectionDB);
        SqlDataAdapter dataAdapter2 = new SqlDataAdapter("SELECT * FROM Film", connectionDB);
        
        // 填充两张表到同一个DataSet
        dataAdapter1.Fill(dataSet, "Genre");
        dataAdapter2.Fill(dataSet, "Film");

        // 创建表间关系,匹配你设置的外键约束
        DataRelation genreToFilmRelation = new DataRelation(
            "GenreToFilm",
            dataSet.Tables["Genre"].Columns["Id"],
            dataSet.Tables["Film"].Columns["Id"]
        );
        dataSet.Relations.Add(genreToFilmRelation);

        // 绑定Genre的数据源
        bindingSource1.DataSource = dataSet.Tables["Genre"];
        dataGridView1.DataSource = bindingSource1;

        // 关键:将Film的BindingSource绑定到父级BindingSource+表间关系,自动联动筛选
        bindingSource2.DataSource = bindingSource1;
        bindingSource2.DataMember = "GenreToFilm";
        dataGridView2.DataSource = bindingSource2;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        connectionDB.Close();
    }
}

可选手动实现方案(适合需要自定义筛选逻辑的场景)

如果你需要手动控制筛选逻辑,可以给dataGridView1添加SelectionChanged事件,代码如下:

private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
    if (dataGridView1.CurrentRow == null) return;
    // 获取选中行的Genre Id
    int selectedGenreId = (int)dataGridView1.CurrentRow.Cells["Id"].Value;
    // 给Film的BindingSource设置筛选条件
    bindingSource2.Filter = $"Id = {selectedGenreId}";
}

注意:如果使用手动筛选方案,你需要将bindingSource1、bindingSource2和dataSet都提升为窗体类的全局成员,避免局部变量被回收导致访问失败。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 21:24:02