【问题标题】:Asp Dropdownlist does not return selected value. (Dropdownlist is Databound)Asp Dropdownlist 不返回所选值。 (下拉列表为数据绑定)
【发布时间】:2015-05-05 07:23:05
【问题描述】:

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

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;
    }
}

【问题讨论】:

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


    【解决方案1】:

    DropDownList1_SelectedIndexChanged 事件中删除if (!IsPostBack) 并且if (!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();
         }
    }
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2011-12-31
        • 1970-01-01
        • 2012-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多