1

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 ??

4
  • kindly share your exception in details Commented Mar 21, 2013 at 8:54
  • what is the exception or error you get?? Commented Mar 21, 2013 at 8:55
  • what is value in combo box? Commented Mar 21, 2013 at 8:55
  • Here are a few tips for the future: debug your code; run the sql command manually; learn about avoiding sql injection. =) Commented Mar 21, 2013 at 8:59

1 Answer 1

2

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();
Sign up to request clarification or add additional context in comments.

1 Comment

thanks very much its work , but now i want to display the value on the dataGridView1.CurrentRow.Cells[2]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.