大家好,我对下拉列表有疑问。我正在将下拉列表与数据源一起使用。如何获得所选的值?
// I need a if statement here because my programme doesn't know which value of dropdown list selected and I don't know how to use this with datasource. if(//if I select quiz 1 from dropdown list ,quiz 1 should list questions.) SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegConnectionString"].ConnectionString); string chooce = "Select Quiz from tblQuiz where Quiz=1 "; SqlCommand userExist = new SqlCommand(chooce, con); con.Open(); int temp = Convert.ToInt32(userExist.ExecuteScalar().ToString()); if (temp == 1) { if (rbList.Items[0].Selected == true) { string cmdStr = "Select Question from tblQuiz where ID=1"; SqlCommand quest = new SqlCommand(cmdStr, con); lblque.Text = quest.ExecuteScalar().ToString(); con.Close(); }
您可以使用来以不同的方式绑定DropDownList List, Dictionary, Enum, DataSet DataTable。 主要在绑定下拉数据源时您必须考虑三件事。
List, Dictionary, Enum, DataSet DataTable
您可以使用以下代码将下拉列表作为数据绑定到数据源datatable:
datatable
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();
如果要处理选择下拉列表,则必须进行更改,然后AutoPostBack="true"可以使用SelectedIndexChangedevent编写代码。
AutoPostBack="true"
SelectedIndexChanged
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { string strQUIZ_ID=DropDownList1.SelectedValue; string strQUIZ_Name=DropDownList1.SelectedItem.Text; // Your code.............. }