-1

I have the following code:

SqlConnection c = new SqlConnection("Data Source=localhost\\sqlexpress;Initial Catalog=BookStoreDataBase1;Integrated Security=True;Pooling=False;");
c.Open();

string raf = string.Format("Select Id from Customer WHERE email='{0}'", DropDownList1.SelectedItem.Text);
SqlCommand comm2 = new SqlCommand(raf, c);
SqlDataReader r = comm2.ExecuteReader();

The object r now has the value of the query which is a row contains that the Id where email equals to random value from drop down list.

what I want is to get the exact value of that "Id" and assign it to label. please help me.

4
  • r.Read(); lbl.Text = r.GetInt32(0).ToString(); Commented Jan 10, 2015 at 9:13
  • 1
    I wonder which tutorial stops at that point without showing also the part where you retrieve the results of your query. Commented Jan 10, 2015 at 9:16
  • stackoverflow.com/questions/27873913/sql-query-and-dropdownlist Commented Jan 10, 2015 at 9:36
  • Tagging is terrible. Question is not related to asp.net, mysql..and try-catch(?!) Commented Jan 10, 2015 at 9:48

2 Answers 2

8

First of all your query is open to SQL Injection attack so change it like this:-

string raf = "Select Id from Customer WHERE email= @Email";
SqlCommand comm2 = new SqlCommand(raf, c);
cmoo2.Parameters.Add("@Email",SqlDbType.NVarchar,20).Value =  
                                           DropDownList1.SelectedItem.Text;

You are fetching just one value so it can be done use ExecuteScalar like this:-

labelid.Text= cmoo2.ExecuteScalar.ToString();

But If you want to use SqlDataReader object then it will return the value when you call the Read method:-

using(SqlDataReader reader= cmoo2.ExecuteReader())
{
    while (reader.Read())
    {
        labelid.Text= reader["Id"].ToString();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

There are lot of examples already in stack overflow regarding this topic you can refer any of that answers or try this

using(SqlDataReader r= cmd.ExecuteReader())
{
    while (r.Read())
    {
        var myString = r.GetString(0); //The 0 stands for "the 0'th column", so the first column of the result.
        labelid.Text=myString;
    }
}

Comments

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.