代码之家  ›  专栏  ›  技术社区  ›  Abe Miessler

如何动态呈现控件?

  •  2
  • Abe Miessler  · 技术社区  · 14 年前

    如何通过代码隐藏中的字符串在网页上呈现ASP.NET控件?

    例如,假设我有下面的ASPX页面:

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="nrm.FRGPproposal.Questionnaire1" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            //want to render a text box here
        </div>
        </form>
    </body>
    </html>
    

    我可以在页面加载事件中做什么来将文本框呈现到DIV中?

    protected void Page_Load(object sender, EventArgs e)
    {
        //what do i do here to render a TextBox in the div from the aspx page?
    }
    
    3 回复  |  直到 8 年前
        1
  •  2
  •   Shirley Charlin Lee    8 年前

    注意,这里可能存在编译问题。但基本上在前面的代码中添加一个占位符控件。
    <%@page language=“c”autoeventwireup=“true”codebehind=“default.aspx.cs”inherits=“nrm.frgpproposal.questionnaire1”%>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:placeholder id="placeHolder" runat="server"/>
        </div>
        </form>
    </body>
    </html>
    

    然后在代码隐藏中以编程方式创建一个文本框。您需要包含System.Web.UI才能获取文本框。 然后将该控件添加到占位符上的控件集合中。以编程方式在文本框上设置您喜欢的任何属性

    protected void Page_Load(object sender, EventArgs e)
    {
        TextBox tb = new TextBox();
        placeHolder.Controls.Add(tb); //tb is referring to the name that you want to name your element. in this example given was TextBox. so the name of text box is tb. 
    
    }
    
        2
  •  2
  •   Sanosay    13 年前

    容易的。

    向DIV元素添加两个属性: <div runat="server" id="myDiv"></div>

    然后

       TextBox tb = new TextBox();
       this.myDiv.Controls.Add(tb);
    

    如果要呈现自定义用户控件,可以使用上面的代码

      MyUserControl control  = (MyUserControl)Page.LoadControl("~/My_VirtualPathToControl");
      this.myDiv.Controls.Add(control);
    

    (必须在ASPX文件中注册控件)

    再想一想。 在页面加载事件上执行代码时要小心。

        3
  •  0
  •   Tehrab    14 年前

    您还需要在 Page_Init 方法,以便在回发时读取控件的状态/值。

    protected void Page_Init(object sender, System.EventArgs e)
    {
        TextBox tb = new TextBox();
        placeHolder.Controls.Add();
    }