问题
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