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

为DataTable函数添加参数,实现ComboBox取值并在DataGridView显示存储过程结果

Solution to Pass ComboBox Parameter to Stored Procedure and Display in DataGridView

Step 1: Modify the Report_with_depo Method to Accept Parameters

Update your DataTable function to take a customerId parameter and pass it to the stored procedure via SQL parameters:

public DataTable Report_with_depo(string customerId)
{
    DAL.DataAccessLayer DAL = new DAL.DataAccessLayer();
    DAL.Open();
    
    // Create SQL parameter matching the stored procedure's @customer_id
    SqlParameter[] parameters = new SqlParameter[1];
    parameters[0] = new SqlParameter("@customer_id", SqlDbType.NVarChar, 50)
    {
        Value = customerId
    };
    
    DataTable dt = DAL.SelectData("Report_with_depo", parameters);
    DAL.Close(); // Ensure connection is closed to prevent leaks
    return dt;
}

Step 2: Update the Button Click Event to Use ComboBox Value

Modify the button's click event handler to retrieve the selected customer ID from the ComboBox and pass it to the updated method:

private void btnShowReport_Click(object sender, EventArgs e)
{
    // Validate ComboBox selection
    if (cboCustomers.SelectedValue == null)
    {
        MessageBox.Show("Please select a customer first.");
        dgv_Report.DataSource = null;
        return;
    }
    
    string selectedCustomerId = cboCustomers.SelectedValue.ToString();
    dgv_Report.DataSource = Report_con.Report_with_depo(selectedCustomerId);
}

Important Notes

  • Ensure your ComboBox is properly configured:
    • If bound to a data source, set ValueMember to customer_id and DisplayMember to the customer's name field (e.g., customer_fullname).
    • Example ComboBox setup (if not already done):
      // Assuming you have a method to get customer data
      DataTable customers = GetCustomers();
      cboCustomers.DisplayMember = "customer_fullname";
      cboCustomers.ValueMember = "customer_id";
      cboCustomers.DataSource = customers;
      
  • The DAL.SelectData method must support accepting an array of SqlParameter to pass to the stored procedure (your existing code indicates it does, since you passed null before).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 10:10:10