为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
ValueMembertocustomer_idandDisplayMemberto 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;
- If bound to a data source, set
- The
DAL.SelectDatamethod must support accepting an array ofSqlParameterto pass to the stored procedure (your existing code indicates it does, since you passednullbefore).
内容的提问来源于stack exchange,提问作者Khayal Ads
相关产品推荐
相关产品推荐

