sql query and dropdownlist

2019-08-16 02:41发布

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 ?

2条回答
Melony?
2楼-- · 2019-08-16 03:08

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

查看更多
We Are One
3楼-- · 2019-08-16 03:20

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;
查看更多
登录 后发表回答