Makinkg动态DropDownList

时间:2011-06-26 09:23:58

标签: c# asp.net dynamic drop-down-menu

我尝试以这种方式制作动态DropDownList

<form id="form1" runat="server">
<asp:DropDownList ID="ddlCategory" runat="server" AutoPostBack="True" 
    onselectedindexchanged="CategoryDropList_SelectedIndexChanged" />
</form>

void DropListInit() 
{
    Dictionary<string, string> dic = new Dictionary<string, string>();
    dic.Add("1","apple");
    dic.Add("2","banana");
    ddlCategory.DataSource = dic;
    ddlCategory.DataTextField = "value";
    ddlCategory.DataValueField = "key";
    ddlCategory.DataBind();
}

protected void Page_LoadComplete(object sender, EventArgs e) 
{
    DropListInit();
}

protected void CategoryDropList_SelectedIndexChanged(object sender, EventArgs e) 
{
    ddlCategory.SelectedValue = ddlCategory.SelectedValue;
}

我发现如果没有这个奇怪的表达式ddlCategory.SelectedValue = ddlCategory.SelectedValue;那就没有用了那么,这个表达意味着什么?或者我做错了什么?

1 个答案:

答案 0 :(得分:1)

将DropListInit移动到Page_load,如下所示;

protected void Page_LoadComplete(object sender, EventArgs e) 
{
    if (!IsPostBack)    
    {
        DropListInit();
    }
}

删除它;

ddlCategory.SelectedValue = ddlCategory.SelectedValue;

应该没事。