Reputation: 69
i am trying to retrieve data from a column in SQL DB depending on the value of combo box in datagridview my code is :
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs
{
using (SqlConnection conn = new SqlConnection("Data Source=POSSERVER\\SQLEXPRESS;Initial Catalog=ms;Integrated Security=True"))
{
string priceselected = ("SELECT price FROM Table_1 WHERE name=" + dataGridView1.CurrentRow.Cells[0].Value.ToString());
SqlCommand cmd = new SqlCommand(priceselected, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
I want to put the price in dataGridView1.CurrentRow.Cells[2]
BUT i get an sqlexception everytime I choose item from the combo box
Any help ??
Upvotes: 1
Views: 1352
Reputation: 263893
If the data type of column Name
is VARCHAR, you need to wrap the value with single quotes because it's a string literal.
string _val = dataGridView1.CurrentRow.Cells[0].Value.ToString();
string priceselected = ("SELECT price FROM Table_1 WHERE name='" + _val + "'");
but the query is vulnerable with SQL Injection
. Please do parameterized the query,eg.
string _val = dataGridView1.CurrentRow.Cells[0].Value.ToString();
string priceselected = ("SELECT price FROM Table_1 WHERE name=@val");
SqlCommand cmd = new SqlCommand(priceselected, conn);
cmd.Parameters.AddWithValue("@val", _val);
conn.Open();
cmd.ExecuteNonQuery();
Upvotes: 2