使用DropDownList的ASP.NET Web表单用户控件无法设置SelectedIndex

时间:2015-12-24 12:44:55

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

我使用DropDownList创建了一个Web表单用户控件。我想更改SelectedIndex的{​​{1}}属性以更改所选索引。

WebUserControl1.ascx:

DropDownList1

WebUserControl1.ascx.cs:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="WebApplication1.ControlUI.WebUserControl1" %>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>

现在我在页面中使用用户控件。

Default.aspx的:

using System;
namespace WebApplication1.ControlUI
{
    public partial class WebUserControl1 : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e) {
            if (IsPostBack) return;
            for (int i = 1; i <= 5; i++) {
                DropDownList1.Items.Add("Test: " + i.ToString());
            }
        }

        public void SetSelectedIndex(int index) {
            DropDownList1.SelectedIndex = index;
        }
    }
}

Default.aspx.cs:

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>
<%@ Register Src="~/ControlUI/WebUserControl1.ascx" TagPrefix="uc1" TagName="WebUserControl1" %>
<asp:Content ID="HeadContent" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
    <uc1:WebUserControl1 runat="server" id="WebUserControl1" />
</asp:Content>

这不起作用。它将 -1 分配到using System; using System.Web.UI; namespace WebApplication1 { public partial class Default : Page { protected void Page_Load(object sender, EventArgs e) { WebUserControl1.SetSelectedIndex(3); } } } 的{​​{1}}属性中。但是,如果我将项添加到标记(SelectedIndex)中的DropDownList中,而不是在代码隐藏文件(DropDownList1)中,则用户控件有效:

WebUserControl1.ascx

但我需要使用codebehind文件添加项目,而不是在标记文件中。为什么不工作?如何解决问题?

1 个答案:

答案 0 :(得分:1)

问题是,包含用户控件(默认)的页面的Page_LoadPage_Load之前为用户控件(WebUserControl1)执行。因此,当从页面调用SetSelectedIndex时,下拉列表在首次构建页面时没有任何列表项。

您可以通过在用户控件生命周期的Init阶段而不是Load阶段创建下拉列表项来非常简单地解决问题:

protected void Page_Init(object sender, EventArgs e) {
  if (IsPostBack) return;
  for (int i = 1; i <= 5; i++) {
    DropDownList1.Items.Add("Test: " + i.ToString());
  }
}