So here's my situation: I have a DropDownList that I populate when a certain event is triggered. To populate it, I execute a SQL query that returns two columns: ID and Name. I bind the Name to the DropDownList using DataSource/DataTextField/DataValueField, but I want to save the ID as well (to use in a second query). How can I do this?
I have tried saving the ID to a hidden input field, because I want to use it but not display it to the user. But input is not a ListControl, so it doesn't work. How do I get the matching ID of the Name selected in the DropDownList?
string strConn = ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT Id, Name FROM Users WHERE Age > 10";
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
NameDropDown.DataSource = objDs.Tables[0];
NameDropDown.DataTextField = "Name";
NameDropDown.DataValueField = "Name";
NameDropDown.DataBind();
NameDropDown.Items.Insert(0, "--Select--");
}
else
{
NameDropDown.Items.Clear();
NameDropDown.Items.Insert(0, "No names found");
}
Consider:
if (objDs.Tables[0].Rows.Count > 0)
{
NameDropDown.DataSource = objDs.Tables[0];
NameDropDown.DataTextField = "Name";
NameDropDown.DataValueField = "ID"; /*why wouldn't this be ID*/
NameDropDown.DataBind();
NameDropDown.Items.Insert(0, "--Select--");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.