Asp.NET DropDownList在PostBack之后重置SelectedIndex

前端之家收集整理的这篇文章主要介绍了Asp.NET DropDownList在PostBack之后重置SelectedIndex前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在网上做了很多研究后,我仍然对这个问题感到难过.我有一个页面,将名称和类别的数量加载到下拉列表中.我只会这样做!(Page.IsPostBack).当AutoPostBack触发SelectedIndex = 0.我尝试了几种不同的东西.这是我的代码

<form id="AddAssignmentForm" runat="server">
<asp:ScriptManager ID="ScriptManager1" EnablePartialRendering="true" runat="server" />

<asp:UpdatePanel ID="CommentUpdate" runat="server">
<ContentTemplate>

Add Comment
<asp:DropDownList ID="ddlCategory" runat="server" Width="206" OnSelectedIndexChanged="ddlCategory_SelectedIndexChanged" AutoPostBack="true" />
<asp:TextBox ID="txtName" runat="server" Width="200" />
<asp:TextBox ID="txtAbbrv" runat="server" Width="200" />
<asp:TextBox ID="txtDescription" runat="server" Width="200" Height="90" TextMode="MultiLine" />

</ContentTemplate>
</asp:UpdatePanel>
</form>

这是后端代码.

private void Page_Load(object sender,System.EventArgs e)
{
    if (!Page.IsPostBack)
    {
        GetCategories();
    }
}

public void GetCategories()
{
    String strsql = @"SELECT Name,Total
                        FROM MyTable";

    if (con.State == ConnectionState.Closed)
        con.Open();

    OleDbCommand cmdsql = new OleDbCommand(strsql,con);
    OleDbDataReader cmdReader = cmdsql.ExecuteReader();

    if (cmdReader.HasRows)
    {
        while (cmdReader.Read())
        {
            ddlCategory.Items.Add(new ListItem(cmdReader["Category_Name"].ToString(),cmdReader["Total"].ToString()));

        }
        ddlCategory.SelectedIndex = -1;
    }


    cmdReader.Close();
    con.Close();
}

public void FillForm(int index)
{
    ListItem item = ddlCategory.Items[index];
    txtName.Text = item.Text + " " + (Convert.ToInt32(item.Value) + 1).ToString();
    txtAbbrv.Text = item.Text.Substring(0,1) + (Convert.ToInt32(item.Value) + 1).ToString();
}

public void ddlCategory_SelectedIndexChanged(Object sender,EventArgs e)
{
    //When I break here SelectedIndex always = 1.
    FillForm(ddlCategory.SelectedIndex);
}

我只是希望能够根据所选索引填充表单,但我似乎无法得到正确的答案.任何帮助表示赞赏.

解决方法

为下拉列表添加AppendDataBoundItems =“true”
原文链接:https://www.f2er.com/aspnet/247933.html

猜你在找的asp.Net相关文章