如果在IsPostBack参数为true时页面加载时以编程方式创建的asp.net控件获取属性(例如Text
)?
架构:
TextBox box = new TextBox(); box.ID = "BoxID"
)SomeControlInPageID.Controls.Add(box)
)"BoxID"
,但我们无法使用BoxID.Text
获取文本属性,因为它是以编程方式创建的!)加入一些文字我尝试使用此代码在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
始终为空值。
答案 0 :(得分:2)
这里的关键是你需要确保每次加载页面时都重新创建动态控件。创建控件后,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>
答案 1 :(得分:1)
请查看aspx页面的 pageLifeCycle 。您必须在Page_Init处理程序中添加文本框。之后,您可以在page_load事件中访问textBox。
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)
}
}
HTH