【问题标题】:Dynamic Dropdownlist is always returning the first value, not the selected value动态下拉列表总是返回第一个值,而不是选定的值
【发布时间】:2016-02-17 01:47:44
【问题描述】:

我有一个问题我一直在与一段时间作斗争,我的动态 DropDownList 总是返回到数据库中的第一个项目,我已经对如何解决这个问题进行了一些研究,包括为页面和 DropDownList 启用 Viewstate 并放置if(!Page.IsPostback) 上的代码,但问题仍然存在!

这是我的代码:

if (!Page.IsPostBack)
{
    string appType2 = Session["applicationType"].ToString();
    if (appType2 == "nur")
    {

        FetchApplicationFeeFromDB("NURSERY");
        this.ddlAppClass.Items.Clear();
        this.ddlApplicationType.Items.Insert(0, "NURSERY SCHOOL");

        string query = string.Format("SELECT [Teaching Room Category] ,[Description] FROM [Corona Schools_ Trust Council$Teaching Room Level] WHERE [Teaching Room Category] = '{0}'", "NURSERY");
        BindDropDownList(this.ddlAppClass, query, "Description", "Teaching Room Category", "---Select---");
    }

}

private void BindDropDownList(DropDownList ddl, string query, string text, string value, string defaultText)
{
    string conString = ConfigurationManager.ConnectionStrings["DatabaseDemo Database NAV (8-0)1"].ConnectionString;
    SqlCommand cmd = new SqlCommand(query);
    using (SqlConnection con = new SqlConnection(conString))
    {
        using (SqlDataAdapter sda = new SqlDataAdapter())
        {
            cmd.Connection = con;
            con.Open();
            ddl.DataSource = cmd.ExecuteReader();
            ddl.DataTextField = text;
            ddl.DataValueField = value;
            ddl.DataBind();
            con.Close();
        }
    }
    ddl.Items.Insert(0, new ListItem(defaultText, "0"));
}

protected void ddlAppClass_SelectedIndexChanged(object sender, EventArgs e){ 
    if (this.ddlAppClass.SelectedIndex != 0) { 
        txtDateOfBirth.Enabled = true; 
    } else { 
        txtDateOfBirth.Enabled = false; 
    } 
} 

我的DropdownList源码:

<asp:DropDownList ID="ddlAppClass" runat="server" AutoPostBack="True" Height="20px" Width="188px" OnSelectedIndexChanged="ddlAppClass_SelectedIndexChanged" EnableViewState="true"></asp:DropDownList>

OnSelectedIndexChanged 代码:

protected void ddlAppClass_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    if (this.ddlAppClass.SelectedIndex != 0) 
    { 
        txtDateOfBirth.Enabled = true; 
    } 
    else 
    {
        txtDateOfBirth.Enabled = false;
    }
}

【问题讨论】:

  • 所以你是说在回发之后,下拉 SelectedIndex 正在重置为第一个 ListItem?
  • DropDownList 中的“动态”是什么?它是在 aspx 上声明的,所以它不是动态的,是吗?
  • 是的,即使我返回并选择所需的项目,在通过单击按钮提交时,下拉的选定项目文本仍将是索引 1 的第一项, selectedindex 零是 ---Select--- 项
  • @TimSchmelter,我说的是动态的,因为项目并不总是相同的,它从会话变量中获取参数值
  • 永远不要使用String.Format或其他字符串连接方法来构建你的sql查询。而是使用参数化查询。

标签: c# asp.net


【解决方案1】:

您需要在每次页面加载时绑定项目,而不仅仅是在 !PostBack 时。当您回发时,页面会从 aspx 重建并(尝试)在代码中设置所选值,但在您的情况下,下拉列表将为空,因为您没有调用 BindDropDownList ,因此无法设置其所选值并且您得到零.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多