【问题标题】:Dynamically load specific User Control from dropdownlist in autopostback从自动回发的下拉列表中动态加载特定的用户控件
【发布时间】:2012-10-31 09:08:33
【问题描述】:

我有一个带有下拉控件的 asp.net 网页,如下所示:

<asp:DropDownList ID="TypeDrp" runat="server" 
        OnSelectedIndexChanged="LoadCorrectForm" AutoPostBack="True">
    <asp:ListItem>X</asp:ListItem>
    <asp:ListItem>Y</asp:ListItem>
    <asp:ListItem>Z</asp:ListItem>
    </asp:DropDownList>

    <br />

    <asp:PlaceHolder ID="PlaceHolder1" runat="server">

    </asp:PlaceHolder>

我想在回发后动态加载 placeholder1 中的控件。它们位于名为“myControls”的文件夹中,如下所示:

XTypeForm.ascx
YTypeForm.ascx
ZTypeForm.ascx

我应该如何正确调用和使用它们? 有人告诉我这样使用:

protected void LoadCorrectForm(object sender, EventArgs e)
{
    string SelectedValue = TypeDrp.SelectedItem.ToString();
    Control userControl = GetSpecificUserControl(SelectedValue);
    PlaceHolder1.Controls.Clear();   // Remove old user control
    PlaceHolder1.Controls.Add(userControl);
}

但它有错误,我不知道如何为我自己的代码更改它?

【问题讨论】:

  • 问题出在 TypeDrp.SelectedItem.ToString()
  • Item 是文本和值的集合。您将值“要加载的控件的名称”放在哪里。如果它在下拉列表的值中,则将其替换为选定的值。

标签: c# asp.net user-controls autopostback


【解决方案1】:

要加载 ascx 用户控件,请使用如下代码:

if(!Page.IsPostBack) 
{ 
   WebUserControl1 uc = 
   (WebUserControl1) Page.LoadControl("WebUserControl1.ascx"); 
   PlaceHolder1.Controls.Add(uc); 
}

【讨论】:

    【解决方案2】:


    <asp:DropDownList ID="TypeDrp" runat="server" 
        OnSelectedIndexChanged="LoadCorrectForm" AutoPostBack="True">
    <asp:ListItem Value="XTypeForm.ascx">X</asp:ListItem>
    <asp:ListItem Value="YTypeForm.ascx">Y</asp:ListItem>
    <asp:ListItem Value="ZTypeForm.ascx" >Z</asp:ListItem>
    </asp:DropDownList>
    

    然后使用

    string SelectedValue = TypeDrp.SelectedValue.ToString();

    它会起作用的。

    【讨论】:

    • 我的控制文件位于另一个名为“myControls”的文件夹中。此外 PlaceHolder1.Controls.Add(....) 不接受字符串数据类型。但是我应该如何调用控制?
    • string SelectedValue = "文件夹名/"+TypeDrp.SelectedValue.ToString();
    • 甚至是string SelectedValue = "~/"+TypeDrp.SelectedValue.ToString();
    【解决方案3】:

    我不确定它是否会起作用,但你可以这样尝试

    string SelectedValue = "foldername/"+TypeDrp.SelectedValue.ToString();
    var lobjucModelTabs = (SelectedValue)LoadControl("~/yourfolder/"+SelectedValue);
    PlaceHolder1.Controls.Clear();
    PlaceHolder1.Controls.Add(lobjucModelTabs );
    

    如果它不起作用
    那么你将不得不使用像这样的 switch 语句。

     string filename = TypeDrp.SelectedValue;
            UserControl userControl;
            switch (filename)
            {
                case "XTypeForm.ascx":
                    UserControl ctrl = (XTypeForm)LoadControl("NewFolder1/XTypeForm.ascx");
                    PlaceHolder1.Controls.Clear();
                    PlaceHolder1.Controls.Add(ctrl);
                    break;
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-12
      • 2018-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-23
      相关资源
      最近更新 更多