0

I'm trying to load the values to label from a SQL query:

sc.Open();
string type = Vehicle_cost.SelectedText;
string query = ("select Type from Vehicle_Registor where Reg_No = '" + type + "';");

SqlCommand cmd1 = new SqlCommand(query, sc);
SqlDataReader sdr = cmd1.ExecuteReader();
label23.Text = sdr.ToString();
sc.Close();
1
  • 3
    SQL Injection alert - you should not concatenate together your SQL statements - use parametrized queries instead to avoid SQL injection Commented Sep 27, 2015 at 9:34

2 Answers 2

1

Try below code..

sc.Open();

string query = @"select Type from Vehicle_Registor where Reg_No = @Reg_No";

SqlCommand cmd1 = new SqlCommand(query, sc);
cmd1.Parameters.AddWithValue("@Reg_No", Vehicle_cost.SelectedText);

SqlDataReader sdr = cmd1.ExecuteReader();
sdr.Read();

label23.Text = sdr[0].ToString();

sc.Close();
Sign up to request clarification or add additional context in comments.

1 Comment

You should check out Can we stop using AddWithValue() already? and stop using .AddWithValue() - it can lead to unexpected and surprising results...
0

Try something like this:

SqlCommand cmd1 = new SqlCommand(query, sc);
using (SqlDataReader sdr = cmd1.ExecuteReader())
{
    while (sdr.Read())
    {
        for (int i = 0; i < sdr.FieldCount; i++)
        {
            label23.text += sdr[i].ToString();
        }
    }
}
sc.Close();

2 Comments

Handle OP's problems properly while answering. First query itself is subject to SQLInjection and why do you think he needs a loop to iterate. One registration per vehicle, concept is simple.
@AmneshGoel If query returns scalar value maybe it's more reasonable to use ExecuteScalar?

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.