Solved

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

Posted on 2004-03-26
22
435 Views
Last Modified: 2010-04-15
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


}
0
Comment
Question by:alain123
  • 11
  • 8
  • 2
  • +1
22 Comments
 
LVL 4

Expert Comment

by:Jarodtweiss
Comment Utility
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 !
0
 
LVL 2

Expert Comment

by:eric_duncan
Comment Utility
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.
0
 
LVL 1

Author Comment

by:alain123
Comment Utility
hello guys,

still none of the two proposed solutions solves the flow problem..  Thank you.. i'll keep trying..
0
 
LVL 20

Accepted Solution

by:
TheAvenger earned 500 total points
Comment Utility
OK, I suggest the following:
- In the main form create only your "original" form. You can even make it static probably, with the needed buttons and fields (you did not provide enough info to know that). Otherwise make the controls be created always (no matter if post back or not)
- Then make the datagrid in a separate form. You can also make it static
- In the button click handler instead of creating the datagrid, redirect the user to another form which will create the datagrid. For this use the this.Server.Transfer() method which will keep all request parameters, etc. etc. and the user will not actually see that this is another page. He can however use back to go back to the "original" form. You can also supply a back button to go to the "original" form using the same method.
0
 
LVL 2

Expert Comment

by:eric_duncan
Comment Utility
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
0
 
LVL 1

Author Comment

by:alain123
Comment Utility
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..
0
 
LVL 20

Expert Comment

by:TheAvenger
Comment Utility
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....
0
 
LVL 1

Author Comment

by:alain123
Comment Utility
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()?

0
 
LVL 20

Expert Comment

by:TheAvenger
Comment Utility
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
0
 
LVL 1

Author Comment

by:alain123
Comment Utility
hmmm.. i'm really trying to avoid session objects...let me see if i find another way..
0
 
LVL 20

Expert Comment

by:TheAvenger
Comment Utility
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.
0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 
LVL 1

Author Comment

by:alain123
Comment Utility
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)
0
 
LVL 1

Author Comment

by:alain123
Comment Utility
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..
0
 
LVL 20

Expert Comment

by:TheAvenger
Comment Utility
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.
0
 
LVL 20

Expert Comment

by:TheAvenger
Comment Utility
Then do all the serialization and other work on the second page.
0
 
LVL 1

Author Comment

by:alain123
Comment Utility
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:

http://www.experts-exchange.com/Programming/Programming_Languages/C_Sharp/Q_20935939.html

http://www.experts-exchange.com/Programming/Programming_Languages/C_Sharp/Q_20933908.html

http://www.experts-exchange.com/Programming/Programming_Languages/C_Sharp/Q_20929010.html
0
 
LVL 20

Expert Comment

by:TheAvenger
Comment Utility
I hope it helped and you succeeded to fix all. Workarounds are unfortunately often needed in our profession :-((
0
 
LVL 1

Author Comment

by:alain123
Comment Utility
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.
0
 
LVL 1

Author Comment

by:alain123
Comment Utility
0
 
LVL 1

Author Comment

by:alain123
Comment Utility
one last question Avenger, does view state remains on dynamic forms?
0
 
LVL 20

Expert Comment

by:TheAvenger
Comment Utility
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
0
 
LVL 1

Author Comment

by:alain123
Comment Utility
Perfect, thanks a lot!
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Mutually exclusive checkbox in a gridview 18 40
Duplicate a row 2 28
VB.NET HttpWebRequest 12 30
COnsume rest client 6 4
Bit flags and bit flag manipulation is perhaps one of the most underrated strategies in programming, likely because most programmers developing in high-level languages rely too much on the high-level features, and forget about the low-level ones. Th…
Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

6 Experts available now in Live!

Get 1:1 Help Now