I have a page which contains a control. This control is repeated on the page several times, showing different data from the database. The end result开发者_开发知识库 resembles a table of data, and I can expand the div to show yet more data in a sort of control panel. Each 'row' has a button, which takes values from the inputs of that particular row, and updates the database with them.
The problem I'm facing is that upon form submission the Page_Load of the page happens before the update method of the control fires (Page_Load > Submit > Page_Load again > fire update method), because the controls need to be loaded again. While the method works as intended (as the input values are kept between page loads), the page contents display the original input value, where as I would like it to display the updated value that is taken from the database (I'd like to avoid changing it as a separate calculation if possible).
e.g. One input contains amount to pay, say 500. If I put in 200, the method will store 200 as payment and the database will be updated to show 300 remaining, but the page load afterwards will still show 500, because the method to pull data was called before the update method.
How can I ensure the update method for the particular row is fired off before the page loads again?
Sounds like you need to check if a postback has happened before binding data to the page. something like
in the page load method, wrap your data fetching logic in
if(!Page.IsPostback)
{
// fetch data
}
It sounds like you just need to redraw your controls again after the update. I would put the logic that generates the controls in it's own method, and call the method on Page_Load and after the update.
The other option is to only set the value of the controls if the page hasn't been posted back yet. If you don't set the values again on postback, whatever is stored in ViewState should populate into the fields.
If you create user controls dynamically then you need to recreate them on each post back but you don't want to load data on each post back, so do as below
aspx : I have panel and I need to add user control dynamically
<asp:Panel ID="Panel1" runat="server">
</asp:Panel>
<asp:Button ID="Button1" runat="server" Text="Button" />
In page load :
protected void Page_Load(object sender, EventArgs e)
{
//create your control on every time
TextBox TextBox1 = new TextBox();
TextBox1.ID = "TextBox1";
Panel1.Controls.Add(TextBox1);
if (Page.IsPostBack)
{
TextBox1.Text = "bind on fist time";
// bind data here..
// only the fist time
}
}
when I click on the button it will go back to server and create dynamic control again and bind text from view state.
Thanks for all your suggestions. After consulting with my colleagues I've decided to use the Jquery AJAX method and Webmethods instead to submit and update the interface dynamically.
精彩评论