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

Winform中DataGridView ComboBox列值变更后自动填充关联列及保存咨询

WinForm DataGridView采购申请录入功能实现方案

前置说明

你已完成的四列预定义DataGridView,默认列名我们按如下约定适配,你可以替换为自己的列名:

  • 第一列ComboBox列:ColItemCode
  • 第二列物品名称文本列:ColItemName
  • 第三列单位文本列:ColUOM
  • 第四列数量文本列:ColQty

1. 加载ComboBox列下拉数据源

在窗体的Load事件中编写代码,从数据库查询物品的三个字段,绑定到ComboBox列:

// 替换为你自己的数据库连接字符串
private string connStr = "你的数据库连接字符串";

private void Form1_Load(object sender, EventArgs e)
{
    // 查询物品表,拼接下拉显示的文本
    string sql = @"SELECT item_code + ' | ' + item_name + ' | ' + uom AS display_text, 
                          item_code, item_name, uom 
                   FROM 你的物品信息表名";
    
    DataTable itemDt = new DataTable();
    using (SqlConnection conn = new SqlConnection(connStr))
    {
        SqlDataAdapter sda = new SqlDataAdapter(sql, conn);
        sda.Fill(itemDt);
    }

    // 绑定到ComboBox列
    DataGridViewComboBoxColumn comboCol = (DataGridViewComboBoxColumn)dataGridView1.Columns["ColItemCode"];
    comboCol.DataSource = itemDt;
    comboCol.DisplayMember = "display_text";
    comboCol.ValueMember = "item_code";
}

如果不需要同时显示三个字段在下拉框,仅显示item code,直接把DisplayMember设为item_code即可

2. 选中物品后自动填充对应字段

给DataGridView绑定EditingControlShowing事件,监听ComboBox的选择变化,自动赋值到当前行的其他列:

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    // 判断当前编辑的是ComboBox列
    if (dataGridView1.CurrentCell.OwningColumn.Name == "ColItemCode" && e.Control is ComboBox comboBox)
    {
        // 先移除之前绑定的事件,避免重复触发
        comboBox.SelectedIndexChanged -= Combo_SelectedIndexChanged;
        comboBox.SelectedIndexChanged += Combo_SelectedIndexChanged;
    }
}

private void Combo_SelectedIndexChanged(object sender, EventArgs e)
{
    ComboBox combo = sender as ComboBox;
    if (combo.SelectedItem != null)
    {
        DataRowView drv = combo.SelectedItem as DataRowView;
        // 获取当前选中行的物品信息
        string itemName = drv["item_name"].ToString();
        string uom = drv["uom"].ToString();
        // 赋值到当前行的对应列
        dataGridView1.CurrentRow.Cells["ColItemName"].Value = itemName;
        dataGridView1.CurrentRow.Cells["ColUOM"].Value = uom;
    }
}

3. 多行添加支持

无需额外编码,只要保证DataGridView的AllowUserToAddRows属性设置为true(默认值即为true),用户点击表格最后一行的占位行即可自动新增空行。

4. 批量保存数据到purchase requisition表

给保存按钮绑定点击事件,遍历所有有效行,参数化插入到数据库:

private void btnSave_Click(object sender, EventArgs e)
{
    // 先做基础校验
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        // 跳过新行占位行
        if (row.IsNewRow) continue;
        
        if (row.Cells["ColItemCode"].Value == null 
            || row.Cells["ColQty"].Value == null 
            || !int.TryParse(row.Cells["ColQty"].Value.ToString(), out int qty) 
            || qty <=0)
        {
            MessageBox.Show("存在无效数据,请检查物品是否选择、数量是否为正整数");
            return;
        }
    }

    // 批量插入数据库
    using (SqlConnection conn = new SqlConnection(connStr))
    {
        conn.Open();
        string insertSql = @"INSERT INTO [purchase requisition] (item_code, item_name, uom, qty)
                             VALUES (@itemCode, @itemName, @uom, @qty)";
        
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (row.IsNewRow) continue;
            
            SqlCommand cmd = new SqlCommand(insertSql, conn);
            cmd.Parameters.AddWithValue("@itemCode", row.Cells["ColItemCode"].Value.ToString());
            cmd.Parameters.AddWithValue("@itemName", row.Cells["ColItemName"].Value.ToString());
            cmd.Parameters.AddWithValue("@uom", row.Cells["ColUOM"].Value.ToString());
            cmd.Parameters.AddWithValue("@qty", int.Parse(row.Cells["ColQty"].Value.ToString()));
            cmd.ExecuteNonQuery();
        }
    }
    MessageBox.Show("保存成功");
    // 保存完成后可以清空表格可选
    dataGridView1.Rows.Clear();
}

注意事项

  • 所有表名、列名、连接字符串请替换为你实际业务中的对应值
  • 可以根据业务需要增加更多校验规则,比如重复物品合并、库存校验等
  • 示例用的是System.Data.SqlClient,如果你用其他数据库(如MySql)替换对应的数据访问类即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 15:24:03