Reputation:
I am using SQL Server 2014 and Visual Studio 2013. I want to write C# code so that user should check checkbox and select an item from combobox then this item will be sent to a stored procedure in SQL Server. In real I want to send parameter to stored procedure from combobox. Code below written by me but does not work well.
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();
}
}
Upvotes: 0
Views: 1192
Reputation: 11
No problem, if SP is without any parameter. It seems your connection string is not properly initialized, otherwise no problem at all. Check the Error type and share. Otherwise OK.
Upvotes: 1
Reputation: 736
It seems that you are not sending any parameter to the Stored procedure
Step 1:
Declare Parameter in your storedprocedure and use it in 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
Then in the code
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();
}
}
Upvotes: 0