Asp Dropdownlist不返回选定的值。 (下拉列表是数据绑定)

时间:2015-05-05 07:23:06

标签: c# sql asp.net data-binding

我创建了一个下拉列表,它从表列加载其数据。现在我想在Index_change_event上选择dropdownlist的值。

protected void Page_Load(object sender, EventArgs e)
{

    string username = Session["username"].ToString();
    SqlConnection con = new SqlConnection("Data Source=DLINK\\SQLEXPRESS;User ID=sa;Password=logmein;Initial Catalog=AndroidAppDB");
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = con;
    con.Open();
    string query = "select Fence_Name from Fence where Username='" + username + "'";
    SqlCommand command = new SqlCommand(query, con);
    DropDownList1.DataSource = command.ExecuteReader();
    DropDownList1.DataValueField = "Fence_Name";
    DropDownList1.DataTextField = "Fence_Name";
    DropDownList1.DataBind();
    con.Close();
    //arr = Session["arr"].ToString();

}

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{


    if (!IsPostBack)
   {


       Label2.Text = DropDownList1.SelectedItem.Value;
}
}

2 个答案:

答案 0 :(得分:1)

if (!IsPostBack)活动中移除DropDownList1_SelectedIndexChangedif (!IsPostBack)应该在Page_Load活动中。

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    Label2.Text = DropDownList1.SelectedItem.Value;
}

protected void Page_Load(object sender, EventArgs e)
{
     if (!IsPostBack)
     {
          string username = Session["username"].ToString();
          SqlConnection con = new SqlConnection("Data Source=DLINK\\SQLEXPRESS;User ID=sa;Password=logmein;Initial Catalog=AndroidAppDB");
          SqlCommand cmd = new SqlCommand();
          cmd.Connection = con;
          con.Open();
          string query = "select Fence_Name from Fence where Username='" + username + "'";
          SqlCommand command = new SqlCommand(query, con);
         DropDownList1.DataSource = command.ExecuteReader();
         DropDownList1.DataValueField = "Fence_Name";
          DropDownList1.DataTextField = "Fence_Name";
        DropDownList1.DataBind();
         con.Close();
     }
}

答案 1 :(得分:0)

你只是在检查!IsPostBack。由于事件是从回发中触发的,因此永远不会运行。另外,请注意不要重新绑定数据源,因此要更改page_load上的选定值。