Can't get 'Text' property with asp-control
Ho开发者_运维技巧w do I get properties (e.g. Text
) with asp.net controls that were created programatically when page loading when IsPostBack parameter is true?
Schema:
- creating control (e.g.
TextBox box = new TextBox(); box.ID = "BoxID"
) - display control in page (e.g.
SomeControlInPageID.Controls.Add(box)
) - user see this textbox (with id
"BoxID"
, but we don't have a possibility to get text property useBoxID.Text
, because it control was created programatically!) in page & puts in it some text - user click in button (asp:Button) in page and start page reloading process
- start Page_Load method & IsPostBack parameter takes the true value
i try to use this code to get
Text
property in Page_Load method, but it's not work...: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
in this code always takes null value.
The key here is you need to make sure you recreate the dynamic controls each time the page is loaded. Once the controls are created, ASP.NET will be able to fill the posted back values into those controls. I've included a full working example below. Notice I add the control in the OnInit
event (which will fire before Page_Load
), and then I can read the value back out in the Page_Load
event if a postback has occurred.
<%@ 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>
Please have a look into pageLifeCycle of an aspx page. You'll have to add the textbox within the Page_Init handler. Afterwards you may access your textBox in page_load event.
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
精彩评论