Link to home
Start Free TrialLog in
Avatar of alain123
alain123

asked on

c#- 1000 points - dynamic controls form flow problem -

hello, i have 1000 (500 on another post) for this problem:

i create all my controls dynamically on oninit(), load them on a form, click submit, .net goes into oninit() again to reload the form, then goes to Button_onclick() where i
create a datagrid dynamically based on the user input from the previus form.

the problem: everytime a user clicks on a datagrid event, it goes into oninit() again and will reload the orinial form, unless i handle that, (which i'm doing badly using a session variable, after he datagrid gets created is set it to true and won;t reload the original form) but i need to be able to have a go back button to go to the orinal form.  your help is highly appreaciatted. thank you.

///the way i handle it now ---------------

override protected void OnInit(EventArgs e)
            {
      if((string)Session["DG"] == (string)"")
                        {
                        
                                                                                  creatForm();
                        
                        }
                        else
                        {

                              CreateDatagrid();

                        }
                                                
}
/////////the flow-------------------------------


oninit()

load form... user enters data..click submit

oninit() again

reload form ...


IsPostBack()
{

}

submitbutton_event(){
capture from form / generate a sql
createdatagrid(sql); //call a function to create a datagrid

}


DataGridsortevent(){
createdatagrid();
}


DataGridpagingevent
{
createdatagrid();
}


GridItemDataBound()
{
//some code


}
Avatar of Jarodtweiss
Jarodtweiss

I'm not sure of that, as I haven't study the flow of web pages, but here are some ideas you could check :

- You are overriding the OnInit method. That method will raise the Init event. It is possible that this method is called all the time but that the event is not raised all the time (do some testing in the OnInit to determine whether or not the Inis has been done)
  --> Try to handle the Init event instead of overriding the OnInit method
- You are overriding the OnInit method but you ARE NOT calling the base class method --> the system may not know that the OnInit has been done
  --> Add a base.OnInit(e) somewhere
- Try to do the same jow in the Load event inside a !IsPostBack test

Hope this can help !
You should move the control creation to the Page_Load event:

private void Page_Load(object sender, System.EventArgs e)
{
     if (!IsPostBack){
          .... load your controls here
     }
}

The IsPostBack property of the Page object indicates whether or not the page is being processed as a result of the postback or not. Since you only want to create the controls once, using !IsPostBack ensures that they will not be recreated each time the page is posted back to the server.

Reloading all of the controls when the user hits the back button is a little bit trickier, because you can get into trouble if you start mucking around with controls whose events are firing on the server side. The safest and easiest, although arguably not the most elegant, solution is to redirect back to the current page when the user clicks the back button:

private void Back_Click(object sender, System.EventArgs e)
{
      Response.Redirect(Request.RawUrl,true);
}

The redirect statement above will stop execution of the current page and refresh the page. Bear in mind that Response.Redirect intentionally throws an exception to cause the redirect, so if you are stepping through your code and suddenly find yourself in an error handling routine, don't be alarmed.
Avatar of alain123

ASKER

hello guys,

still none of the two proposed solutions solves the flow problem..  Thank you.. i'll keep trying..
ASKER CERTIFIED SOLUTION
Avatar of TheAvenger
TheAvenger
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Using Server.Transfer() is a good solution - that probably is cleaner than my solution above. If that doesn't work, you might need to provide some more information about your specific issue because one of these solutions should work given the information you've given.

Eric
hello Avenger,

i was really trying to keep this into only one page and not create/transfer to other pages..

about the statics fiellds, all my fields are being created dinamically based on an xml spec.. the datagrid too..

since the form is dynamic, i need to recreate it on ispostback in order to grab the values, and then i guess do a server transfer to another page to create the datagrid is what you mean?


let me try something, i'll get back to you..
OK, as your controls are all dynamic, you need to recreate them every time - no matter if post back or not. Otherwise the click event will not be fired.

So, in the Page_Load (or OnInit, but I suggest Page_Load) create the controls. Then in the handler of the click event transfer to the other page.

Btw I think it would be better to use two pages - otherwise the code will be a lot lot....
so after server.transfer, how do i access a value created and assigned from the previous form?  for example a string..

btw, all my main forms are a BaseControls type

public class Form1: Classes.BaseControls ...

public class Form2: Classes.BaseControls  ..
///

public class BaseControls : Page
      {
            
            public Label lblError = new Label();
            public Label lblSpace = new Label();
            public Label LblMessage = new Label();
            public Control objControl = new Control();
            public PlaceHolder OMMain = new PlaceHolder();
            public Control parsedControl = new Control();
            public string treeviewsource;
                                public string SQL;


///

 but after server.transfer, i lose their values ..  shouldn't they be alive after a server.transfer()?

No, they are not because you go to a different object instance. You can send the values through the session collection. Something like:

in the first form:

this.Session["Param1"] = value1;
....

in the second form:
val1 = (type)this.Session["Param1"];
this.Session["Param1"] = null;  // To clear it
hmmm.. i'm really trying to avoid session objects...let me see if i find another way..
The session object will be used very shortly this way - only until the transfer is made. It should not be a problem for the server, if this is your concern.
it's just that i don't think session objects are reliable, i think they should be avoided as much as possible.. until now i have been able to avoid them..

take a look at this..

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon/html/vbtskpassingvaluesbetweenwebformspages.asp

shouldn't this work? (not working for me so far)
it gets more complicated... i'm using serialization and assign values to an serialized object before creating the form.. these object values are being used across my application centralized classes,  i'm loosing all those values as well..
You can put all of them in the session. Btw I don't think session objects are unreliable - it's just not possible to make a huge and complex application without session objects.

The link you provided is when you make a new round trip to the client. In your case you don't do this....

Can you try to redirect the page and then in the new page try to get the values like:

val = this.Request["lblError"];

instead of:

this.lblError.Text. This should work actually.
Then do all the serialization and other work on the second page.
if i define them at the public level on Form1, then i  can access them and assign their values to the local objects on Form2...   i guess i have no other options besides to do it on 2 pages, .. let's close this questions.

post a comment on this links so i can give you the points:

https://www.experts-exchange.com/questions/20935939/dynamic-control-creation-flow-problem.html

https://www.experts-exchange.com/questions/20933908/datagrid-dynamic.html

https://www.experts-exchange.com/questions/20929010/flow-problem.html
I hope it helped and you succeeded to fix all. Workarounds are unfortunately often needed in our profession :-((
it did helped, it's a solution to a pulling hair problem... i appreciatte it, to Eric and Jarod too thank you for your help. i hope if someone comes into the same situation they come accross this post to solve this issue. thank you.
one last question Avenger, does view state remains on dynamic forms?
Yes, but it's a little bit complicated. The problem is that static controls are recreated in the OnInit, the ViewState is reviewed immediately after that, then Page_Load is started (which normally creates the dynamic controls) and then the ViewState is further processed. However if you mix the dynamic and static controls, the ASP.NET cannot handle the controls correctly and some problems occure.

Have a look here for some more information:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon/html/vbtskAddingControlsToWebFormsPageProgrammatically.asp
Perfect, thanks a lot!