使用DropDownList';的ASP.NET web窗体用户控件;无法设置s SelectedIndex

本文关键字:控件 用户 窗体 设置 SelectedIndex web DropDownList NET ASP 使用 | 更新日期: 2023-09-27 18:27:54

我创建了一个带有DropDownList的web表单用户控件。我想更改DropDownList1SelectedIndex属性以更改所选索引。

WebUserControl1.ascx:

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

WebUserControl1.ascx.cs:

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

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

默认.aspx:

<%@ 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>

默认.aspx.cs:

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赋值到DropDownList1SelectedIndex属性中。但是,如果我在标记(WebUserControl1.ascx)中而不是在代码绑定文件(WebUserControl1.ascx.cs)中向DropDownList添加项目,则用户控件可以工作:

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

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

使用DropDownList';的ASP.NET web窗体用户控件;无法设置s SelectedIndex

问题是包含用户控件(默认值)的页面的Page_Load在用户控件(WebUserControl1)的Page_Load之前执行。因此,当从页面调用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());
  }
}