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

C#实现DataGridView外键关联:点击按钮展示指定客户价格列表

客户价格列表项目实现方案(非MVC/Entity Framework版)

核心实现逻辑

通过ADO.NET直接操作SQL Server数据库,从主窗体获取选中客户的ClientID,传递到新窗体后执行关联查询,将结果绑定到DataGridView展示。


1. 主窗体(客户列表)代码

假设主窗体包含:

  • DataGridView 控件(命名:dgvClients)
  • Button 控件(命名:btnShowPrices)

加载客户列表到DataGridView

在主窗体的Load事件中添加以下代码,用于初始化客户数据:

private void MainForm_Load(object sender, EventArgs e)
{
    // 替换为你的SQL Server连接字符串
    string connString = "Server=你的服务器名;Database=你的数据库名;Integrated Security=True;";
    string query = "SELECT ClientID, ClientName, ContactInfo FROM Clients"; // 根据你的Clients表字段调整

    using (SqlConnection conn = new SqlConnection(connString))
    {
        SqlDataAdapter adapter = new SqlDataAdapter(query, conn);
        DataTable dtClients = new DataTable();
        adapter.Fill(dtClients);
        
        dgvClients.DataSource = dtClients;
        // 设置主键列不可见(可选,根据需求调整)
        dgvClients.Columns["ClientID"].Visible = false;
    }
}

「显示价格列表」按钮点击事件

点击按钮时获取选中行的ClientID,打开价格列表窗体并传递参数:

private void btnShowPrices_Click(object sender, EventArgs e)
{
    // 判断是否选中有效行
    if (dgvClients.SelectedRows.Count == 0)
    {
        MessageBox.Show("请先选中一个客户");
        return;
    }

    // 获取选中行的ClientID(假设ClientID是int类型,根据实际字段类型调整)
    int clientId = Convert.ToInt32(dgvClients.SelectedRows[0].Cells["ClientID"].Value);
    
    // 打开价格列表窗体并传入ClientID
    PriceListForm priceForm = new PriceListForm(clientId);
    priceForm.ShowDialog();
}

2. 价格列表窗体(PriceListForm)代码

新建Windows窗体,添加DataGridView控件(命名:dgvPrices),并在窗体类中添加构造函数接收ClientID:

窗体构造函数与数据加载逻辑

public partial class PriceListForm : Form
{
    private int _clientId;

    // 构造函数接收ClientID
    public PriceListForm(int clientId)
    {
        InitializeComponent();
        _clientId = clientId;
    }

    private void PriceListForm_Load(object sender, EventArgs e)
    {
        string connString = "Server=你的服务器名;Database=你的数据库名;Integrated Security=True;";
        // 关联三张表的查询语句(假设表为Clients、ClientPrices、Services,根据你的实际表名调整)
        string query = @"
            SELECT cp.PriceID, cp.ServiceID, s.ServiceName, cp.UnitPrice, cp.DiscountRate
            FROM ClientPrices cp
            JOIN Services s ON cp.ServiceID = s.ServiceID
            WHERE cp.ClientID = @ClientID";

        using (SqlConnection conn = new SqlConnection(connString))
        {
            SqlCommand cmd = new SqlCommand(query, conn);
            // 添加参数防止SQL注入
            cmd.Parameters.AddWithValue("@ClientID", _clientId);

            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataTable dtPrices = new DataTable();
            adapter.Fill(dtPrices);

            dgvPrices.DataSource = dtPrices;
            // 根据需求调整列的显示设置
            dgvPrices.Columns["PriceID"].Visible = false;
        }
    }
}

关键注意事项

  • 连接字符串配置:建议将连接字符串放在App.config中,方便后续修改:
    <connectionStrings>
      <add name="PriceListDB" connectionString="Server=你的服务器名;Database=你的数据库名;Integrated Security=True;" providerName="System.Data.SqlClient" />
    </connectionStrings>
    
    代码中通过ConfigurationManager.ConnectionStrings["PriceListDB"].ConnectionString获取。
  • SQL注入防护:始终使用参数化查询(如代码中的@ClientID),避免拼接SQL字符串。
  • 资源释放:使用using语句自动释放SqlConnection、SqlCommand等资源,防止数据库连接泄漏。
  • 字段适配:所有表字段名(如ClientName、ServiceName)请根据你实际创建的三张表结构调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 02:45:34