簡體   English   中英

不能設置帶有DropDownList的SelectedIndex的ASP.NET Web窗體用戶控件

[英]ASP.NET web forms user control with DropDownList's SelectedIndex cannot be set

我用DropDownList創建了一個Web窗體用戶控件。 我想更改DropDownList1 SelectedIndex屬性以更改選定的索引。

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

現在,我在頁面中使用用戶控件。

Default.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>

Default.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分配給DropDownList1 SelectedIndex屬性。 但是,如果將項目添加到標記中的DropDownList( WebUserControl1.ascx )中,而不是在代碼隱藏文件( WebUserControl1.ascx.cs )中,則用戶控件會起作用:

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

但是我需要使用代碼隱藏文件(而不是標記文件)添加項目。 為什么不起作用? 如何解決問題?

問題是, Page_Load包含用戶控件(默認)的頁面之前執行Page_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());
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM