Reputation: 3
I have written the below code in dataGridView celldouble click event with full row select, so whenever I double click the row it should feed back to textbox and comboxes.
But I'm getting the error "System.Data.SqlClient.SqlException: 'Invalid column name 'new1'.'" where new 1 is the genderm in this field. Instead of reading combobox2 's value it's reading genderm
SqlConnection conn = new SqlConnection(config.constring);
SqlCommand command = new SqlCommand("SELECT rangemaster.code as
code, rangemaster.genderm as [Male], rangemaster.genderf as [Female],
rangemaster.age as [Age], rangemaster.agerange as [Age Range],
rangemaster.commonrange as [Common Range], testmaster.testname as
[Test Name] FROM rangemaster LEFT JOIN testmaster ON rangemaster.code =
testmaster.code where rangemaster.code = " +
dataGridView1.SelectedRows[0].Cells[0].Value.ToString() + "", conn);
conn.Open();
using (SqlDataReader reader = command.ExecuteReader())
while (reader.Read())
{
name4.Text = reader[0].ToString();
textBox4.Text = reader[1].ToString();
textBox3.Text = reader[2].ToString();
comboBox1.SelectedIndex = Convert.ToInt32(reader[3]) - 1;
textBox5.Text = reader[4].ToString();
textBox1.Text = reader[5].ToString();
comboBox2.SelectedIndex = Convert.ToInt32(reader[6]) - 1;
}
conn.Close();
Upvotes: 0
Views: 1234
Reputation: 3
The problem is that you are missing the quotes. You have to add "" at the end.
SqlCommand command = new SqlCommand("SELECT rangemaster.code as ... where rangemaster.code = @param");
command.Parameters.Add("@param",SQlDbType.Nvarchar).Value = dataGridView1.SelectedRows[0].Cells[0].Value.ToString() + "", conn);
You can use this but i would suggest you to use parameters. They can save you from a SQL Injection.
Use Something Like this:
SqlCommand command = new SqlCommand("SELECT rangemaster.code as ... where rangemaster.code = @param");
command.Parameters.Add("@param",SQlDbType.Nvarchar).Value = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
Always practice this for more secure code.
Upvotes: 0
Reputation: 17858
You arent putting in quotes..
your code
"..where rangemaster.code = " +
dataGridView1.SelectedRows[0].Cells[0].Value.ToString() + "", conn);
If the content of the cell is new1 then it will read where rangemaster.code = new1
.. you need to put quotes round it, what would be better would be to use parameters and save from injection
so
SqlCommand command = new SqlCommand("SELECT ... where rangemaster.code = @code", conn);
command.Parameters.AddWithValue("@code",dataGridView1.SelectedRows[0].Cells[0].Value.ToString());
Upvotes: 0
Reputation: 14389
The problem is that you are missing quotes. In any case the correct solution, is to use SQL parameters like:
SqlCommand command = new SqlCommand("SELECT rangemaster.code as ... where rangemaster.code = @param");
command.Parameters.Add("@param",SQlDbType.Nvarchar).Value = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
Upvotes: 4