sql query and dropdownlist

有些话、适合烂在心里 提交于 2019-12-25 05:35:25

问题


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:


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;



回答2:


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



来源:https://stackoverflow.com/questions/27873913/sql-query-and-dropdownlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!