How to change property of UserControl on PostBack?
Let's say I have a page with my custom UserControl
(containing only asp:Literal
and some string property) and a button. Now I want to change Literal's text on button click, so I change my control's string property in button clicked event. Like this:
//in aspx
protected void Button1_Click(object sender, EventArgs e)
{
testControl.Text = "triggered";
}
The problem is my Literal remains unchanged because Page_Load
event fire开发者_运维知识库s first and creates my custom control, then Button_Clicked
fires and changes property but as control is already created, it does nothing. This is my control's code behind:
public partial class TestControl : System.Web.UI.UserControl
{
public string Text { get; set; } }
protected void Page_Load(object sender, EventArgs e)
{
lblTest.Text = Text;
}
}
I figured out that if I move any logic in custom control from Page_Load
to property setter it will change like intended. Like this:
public string Text { get { return lblTest.Text; } set { lblTest.Text = value; } }
Is there any other (better) way to do this? My real problem involves much more complicated controls than described here, but problems remains the same: on any postback all properties set in event handlers are ignored.
Moving all logic from Page_Load
to Page_PreRender
solved the problem. Now properties are set before logic executes. I'll wait for other answers to check if there is better solution and if there are any drawbacks of using Page_PreRender
.
This video might help: How Do I: Persist the State of a User Control During a Postback
精彩评论