Obtaining Selected Value from DropdownList with Datasource
DropdownList is an HTML element that allows users to select a single value from a list of options. When using a DropdownList with a datasource, it's essential to understand how to retrieve the selected value to perform various operations in your code.
To bind a DropdownList to a datasource, such as a DataTable or a SqlDataSource, you must specify three properties:
For example, the following code binds a DropdownList to a DataTable using the "Quiz_ID" field as the value field and the "Quiz_Name" field as the text field:
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();
Once the DropdownList is bound to the datasource, you can retrieve the selected value through the SelectedIndexChanged event. This event is triggered whenever the user selects a different item from the list. Within this event handler, you can access the selected value using:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { string selectedQuizID = DropDownList1.SelectedValue; string selectedQuizName = DropDownList1.SelectedItem.Text; // Perform your code here... }
This code captures the "Quiz_ID" of the selected quiz and stores it in the "selectedQuizID" variable. Additionally, it obtains the displayed text of the selected item and stores it in the "selectedQuizName" variable. You can now use these values to perform any necessary operations based on the user's selection.
The above is the detailed content of How Do I Retrieve the Selected Value from a Datasource-Bound DropdownList?. For more information, please follow other related articles on the PHP Chinese website!