Reputation: 19
In Windows form application, I want to add The Result of a Select SQL Query into another table.
This the code behind the button click, I think the SQL query is wrong somewhere. please help
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=HOME;Initial
Catalog=Test;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("insert into list (pname, pprice)
(select pname, pprice from products where pid='" +textBox1.Text+"')", con);
MessageBox.Show("Product Added");
con.Close();
}
Upvotes: 0
Views: 1029
Reputation: 1679
private void button1_Click(object sender, EventArgs e)
{
SqlDataAdapter SDA = new SqlDataAdapter();
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection("Data Source=HOME;Initial
Catalog=Test;Integrated Security=True");
SqlCommand cmd = new SqlCommand("insert into list (pname, pprice)
select pname, pprice from products where pid='" +textBox1.Text+"'", con);
con.Open();
SDA.SelectCommand = cmd;
SDA.Fill(dt);
con.Close();
MessageBox.Show("Product Added");
}
You made following mistakes in your code
1 : you open connection before creating of sqlcommand object
2: you did not write code to execute the query properly
3: you also put parenthesis before the select statement
Note: Make Sure textBox1.Text is not null or empty also you should use paramterize query
Upvotes: 1