Question:
How can you access the value selected in a DropDownList bound to a data source?
Answer:
Binding a DropDownList to a data source involves three key elements:
Binding the DropDownList:
To bind a DropDownList to a DataTable data source:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString); SqlCommand cmd = new SqlCommand("Select * from tblQuiz", con); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); DropDownList1.DataTextField = "QUIZ_Name"; DropDownList1.DataValueField = "QUIZ_ID"; DropDownList1.DataSource = dt; DropDownList1.DataBind();
Getting the Selected Value:
To obtain the selected value after binding:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { string selectedValue = DropDownList1.SelectedValue; string selectedText = DropDownList1.SelectedItem.Text; }
Using this approach, you can access the selected value and associated text of the DropDownList when the user makes a selection.
The above is the detailed content of How Do I Retrieve the Selected Value from a Data-Bound DropDownList?. For more information, please follow other related articles on the PHP Chinese website!