如何通过参数化存储过程填充列表框

本文关键字:填充 列表 存储过程 何通过 参数 | 更新日期: 2023-09-27 18:31:36

我有一个Winforms应用程序和一个employeeListBox,DepartmentComboBox和一些文本框来显示员工信息,例如fNameTextbox,lNameTextBox.....

我想通过部门组合框选定值填充员工列表框,并从员工列表框中填充文本框。我有这个存储过程来选择部门的员工

ALTER PROCEDURE [dbo].[selectEmployee] 
   @departID int
-- Add the parameters for the stored procedure here
AS
   -- SET NOCOUNT ON added to prevent extra result sets from
   -- interfering with SELECT statements.
   SET NOCOUNT ON;
   -- Insert statements for procedure here
   declare @ErrorCode int

   BEGIN TRANSACTION
      if ( @ErrorCode = 0 )
      Begin
        SELECT 
            EmpID, firstname, lastName, dateOfBirth, Gender, contactNumber, maritalStatus, 
            emailAddress, resentAddress, permanentAddress, nationality, bloodGroup, 
            qualification, Skills, Experience, joiiningdate, probation, departmentID, 
            Salary, paymentMode, active 
        FROM Employee
        WHERE departmentID = @departID
set @ErrorCode = @@error
      End
      if ( @ErrorCode = 0 )
     COMMIT TRANSACTION
      else
         ROLLBACK TRANSACTION
     return @ErrorCode   

为了填充列表框,我写了这段代码

    private void selectEmployee(int departID)
    {
        string connString = BL.dbConn.ConnStr;
        DataSet ds = new System.Data.DataSet();
        SqlConnection conn = new SqlConnection(connString);
        conn.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.CommandType = System.Data.CommandType.StoredProcedure;
        cmd.CommandText = "dbo.selectEmployee";
        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        adapter.Fill(ds);
        listBox1.DataSource = ds.Tables[0].DefaultView;
        listBox1.ValueMember = "EmpID";
        listBox1.DisplayMember = "firstname";
        cmd.Parameters.Clear();
        conn.Close();
        conn.Dispose();
    }

我不知道如何将部门ID传递给存储过程 其次如何从列表框数据集填充文本框?

如何通过参数化存储过程填充列表框

要传递部门ID,您需要创建SQL参数并需要使用SQL命令附加将为您完成工作

您在代码中忘记的事情是da.SelectCommand = cmd;指定选择命令

        SqlConnection conn = new SqlConnection(connString);
        SqlCommand cmd = new SqlCommand();
        SqlDataAdapter da = new SqlDataAdapter();
        DataTable dt = new DataTable();
        try
        {
            conn.Open();
            cmd = new SqlCommand("dbo.selectEmployee", conn );
            cmd.Parameters.Add(new SqlParameter("@departID", value);
            cmd.CommandType = CommandType.StoredProcedure;
            da.SelectCommand = cmd;
            da.Fill(dt);
            dataGridView1.DataSource = dt;
        }
        catch (Exception x)
        {
            MessageBox.Show(x.GetBaseException().ToString(), "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        finally
        {
            cmd.Dispose();
            conn.Close();
        }

为了在文本框中填充值,您能否发布您想要执行的代码或示例,然后我可以进一步帮助您

您需要执行以下操作才能将 DepartmentId 添加到存储过程中:

cmd.Parameters.Add(new SqlParameter("@departID", departID));