【问题标题】:Can't get 'Text' property with asp-control无法使用 asp-control 获取“文本”属性
【发布时间】:2011-07-06 08:03:32
【问题描述】:

当 IsPostBack 参数为 true 时,如何使用在页面加载时以编程方式创建的 asp.net 控件获取属性(例如 Text)?

架构:

  • 创建控件(例如TextBox box = new TextBox(); box.ID = "BoxID"
  • 页面中的显示控件(例如SomeControlInPageID.Controls.Add(box)
  • 用户在页面中看到此文本框(id 为"BoxID",但我们无法获取使用BoxID.Text 的文本属性,因为它是通过编程方式创建的!)并在其中放入一些文本
  • 用户单击页面中的按钮 (asp:Button) 并开始页面重新加载过程
  • 启动Page_Load方法&IsPostBack参数取真值
  • 我尝试使用此代码在 Page_Load 方法中获取 Text 属性,但它不起作用...:

    void Page_Load()
    {
       if (Page.IsPostBack)
       {
        TextBox box = SomeControlInPageID.FindControl("BoxID") as TextBox;
        string result = box.Text;
       }
       else
       {
        // creating controls programatically and display them in page
        ...
       }
    }
    

此代码中的box.Text 总是取空值。

【问题讨论】:

  • 在这种情况下,您将创建文本框控件。可能这应该是页面的 Init 事件。您需要在回发期间访问它们之前重新创建控件
  • @Roman 遇到这个问题了吗?

标签: asp.net text get properties


【解决方案1】:

这里的关键是您需要确保在每次加载页面时重新创建动态控件。创建控件后,ASP.NET 将能够将回发的值填充到这些控件中。我在下面包含了一个完整的工作示例。请注意,我在OnInit 事件中添加了控件(它将在Page_Load 之前触发),然后如果发生回发,我可以在Page_Load 事件中读取值。

<%@ Page Language="C#" AutoEventWireup="true" %>
<html>
<body>
    <form id="form1" runat="server">
    <asp:Panel ID="myPanel" runat="server" />
    <asp:Button ID="btnSubmit" Text="Submit" runat="server" />
    <br />
    Text is: <asp:Literal ID="litText" runat="server" />
    </form>
</body>
</html>
<script runat="server">
protected void Page_Load(object sender, System.EventArgs e)
{
    if(Page.IsPostBack)
    {
        var myTextbox = myPanel.FindControl("myTextbox") as TextBox;
        litText.Text = myTextbox == null ? "(null)" : myTextbox.Text;
    }
}

protected override void OnInit(EventArgs e)
{
    AddDynamicControl();
    base.OnInit(e);
}

private void AddDynamicControl()
{
    var myTextbox = new TextBox();
    myTextbox.ID = "myTextbox";
    myPanel.Controls.Add(myTextbox);
}
</script>

【讨论】:

    【解决方案2】:

    请查看 aspx 页面的 pageLifeCycle。您必须在 Page_Init 处理程序中添加文本框。之后您可以在 page_load 事件中访问您的文本框。

    protected void Page_Init(object sender, EventArgs e)
    {
        TextBox tb = new TextBox();
        tb.ID = "textbox1";
        tb.AutoPostBack = true;
        form1.Controls.Add(tb);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        /// in case there are no other elements on your page
        TextBox tb = (TextBox)form1.Controls[1];
        /// or you iterate through all Controls and search for a textbox with the ID 'textbox1'
        if (Page.IsPostBack)
        {
            Debug.WriteLine(tb.Text);   /// only for test purpose (System.Diagnostics needed)
        }        
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-19
      • 2013-05-07
      • 2015-06-14
      相关资源
      最近更新 更多