0

I have a drop down list which has the values of column's table.

and I have the following statement in c#:

string raf = string.Format("select Id from Customer WHERE email="dropdownlist1");

how can assign the value of the drop down list to email ?

1
  • make sure you use parameters Commented Jan 10, 2015 at 7:37

2 Answers 2

3

You need to use .SelectedValue property to fetch the value of dropdown:-

string raf = string.Format("select Id from Customer WHERE email={0}",
                                  dropdownlist1.SelectedValue);

For fetching dropdown text:-

string raf = string.Format("select Id from Customer WHERE email={0}",
                                    dropdownlist1.SelectedItem.Text);

Also, Note you need a place holder like {0}, when using String.Format.

Though as per your query, you are mostly hitting a database, so beware of SQL Injection, use parameterized query like this:-

  string raf = select Id from Customer WHERE email=@DropdownText;
  SqlCommand cmd = new SqlCommand(raf,conn);
  cmd.Parameters.Add("@DropdownText",SqlDbType.NVarchar,20).Value =
                                      dropdownlist1.SelectedItem.Text;
Sign up to request clarification or add additional context in comments.

8 Comments

The above solution is open to SQL injection attack. The proper way is to use sql parameter
@TienDinh - Yeah OP didn't mentioned that he is going to hit DB but as per his statement I should have considered that and BTW was updating that only when you commented. Thanks.
how can i display the value of the selected Id into a label ?
@RefaatKh - Simple: LabelId.Text = dropdownlist1.SelectedItem.Text;
no, i mean the "id" where the value = dropdownlist.
|
1

try this

string raf = string.Format("select Id from Customer 
WHERE email='{0}'",dropdownlist1.SelectedValue));

{0} Means Your are fetching First Argument of string.Format method

Beware of SQL Injection Always Use SQL Parameters

1 Comment

You don't need ToString(), SelectedValue property returns String.

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.