我正在使用SQL Server 2014和Visual Studio 2013.我想编写C#代码,以便用户选中复选框并从组合框中选择一个项目,然后此项目将被发送到SQL Server中的存储过程。实际上我想从combobox向存储过程发送参数。以下代码由我撰写,但效果不佳。
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked) ;
SqlConnection con = new SqlConnection(@"Data Source=USER-PC\----);
SqlCommand Cmd = new SqlCommand("select_Info_Person", con);
Cmd.CommandType = CommandType.StoredProcedure;
con.Open();
DataTable dt = new DataTable();
using(SqlDataAdapter da = new SqlDataAdapter(Cmd))
{
da.Fill(dt);
comboBox1.DisplayMember = "Person_Expert";
comboBox1.DataSource = dt;
con.Close();
}
}
答案 0 :(得分:1)
没问题,如果SP没有任何参数。看来您的连接字符串未正确初始化,否则完全没问题。检查错误类型并分享。否则OK。
答案 1 :(得分:0)
您似乎没有向存储过程发送任何参数
第1步:
在storedprocedure中声明参数并在where condition ..
中使用它CREATE PROCEDURE select_Info_Person
-- Add the parameters for the stored procedure here
@p1 int = 0
AS
BEGIN
-
-- Insert statements for procedure here
Select * from PersonMaster where personID=@p1
END
GO
然后在代码中
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox.Checked) ;
SqlConnection con = new SqlConnection(@"Data Source=USER-PC\----");
SqlCommand Cmd = new SqlCommand("select_Info_Person", con);
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Parameters.AddWithValue("@p1", comboBox1.SelectedValue.ToString());
// or if you dont have value feild
// Cmd.Parameters.AddWithValue("@p1", comboBox1.Selecteditem.Text.ToString());
con.Open();
DataTable dt = new DataTable();
using (SqlDataAdapter da = new SqlDataAdapter(Cmd))
{
da.Fill(dt);
//I cannot understand what you are doing using below
// comboBox1.DisplayMember = "Person_Expert";
// comboBox1.DataSource = dt;
// con.Close();
}
}