Solved

processing dynamic controls

Posted on 2004-04-26
16
166 Views
Last Modified: 2012-05-04
Hi,

I am facing this problem, which is about processing dynamic controls.
I created a method that declare 2-D array of TextBox and insert them in ASPX page using C# (for Crossword Grid).

the problem is that when i want to process these TextBoxs it gives me an error saying:
"Object reference not set to an instance of an object."

My problem happens when i try to click on Button2 (Click_Button2)

I tried many ways to solve this problem but i could not. So, I need your help in it.

This is my source code:


      public class WebForm1 : System.Web.UI.Page
      {
            protected System.Web.UI.WebControls.Button Button1;
            protected System.Web.UI.WebControls.Button Button2;
            protected System.Web.UI.WebControls.TextBox TextBox1;
            HtmlForm Form;
            
            TextBox[][] tb; // this is my TextBoxes
            
            
            public void create_grid(int size)
            {
                  tb = new TextBox[size+1][];
                  
                  for(int i = 0;i<tb.Length;i++)
                        tb[i] = new TextBox[size+1];
                        
                  for(int i=0;i<tb.Length;i++)
                        for(int j=0;j<tb.Length;j++)
                              tb[i][j] = new TextBox();

                  for (int i = 1; i<tb.Length; i++)
                        for(int j=1;j<tb.Length;j++)
                        {
                              int left = 25+((j-1)*25);
                              int top = 25+((i-1)*25);
                              tb[i][j].Style.Add("POSITION","absolute");
                              tb[i][j].Style.Add("HEIGHT","25");
                              tb[i][j].Style.Add("WIDTH","25");
                              tb[i][j].Style.Add("LEFT",left.ToString());
                              tb[i][j].Style.Add("TOP",top.ToString());
                              tb[i][j].ID = "textBoxddf"+i+j;
            

//////////////////////////////////////  Adding them to the Form ///////////////////////////                                              Form.Controls.Add(tb[i][j]);

                              
                              
                        }

                  tb[1][1].Text = "T";
                  tb[2][2].Style.Add("Background","Black");
      
                  tb[2][2].ReadOnly = true;
                  if(tb[1][1].Text == "T")
                        tb[3][3].Text = "F";
                  

            }
            private void Page_Load(object sender, System.EventArgs e)
            {
                  
            }

            #region Web Form Designer generated code
            override protected void OnInit(EventArgs e)
            {
                  //
                  // CODEGEN: This call is required by the ASP.NET Web Form Designer.
                  //
                  InitializeComponent();
                  base.OnInit(e);
            }
            
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {    
                  this.Button1.Click += new System.EventHandler(this.Button1_Click);
                  this.Button2.Click += new System.EventHandler(this.Button2_Click);
                  this.Load += new System.EventHandler(this.Page_Load);
                  Form = ( System.Web.UI.HtmlControls.HtmlForm )this.FindControl( "Form1" );
                  

            }
            #endregion

            private void Button1_Click(object sender, System.EventArgs e)
            {
                  create_grid(int.Parse(TextBox1.Text));
            }

            private void Button2_Click(object sender, System.EventArgs e)
            {
                  
                  if(tb[3][3].Text.Equals("3")) tb[3][1].Text = "T";
                  else tb[3][1].Text = "F";
            }
      }
}
0
Comment
Question by:shams_sa
  • 8
  • 6
16 Comments
 
LVL 1

Expert Comment

by:warmach
Comment Utility
Your TextBox[][] tb variable is not being saved each time the page loads.  This is the way ASP.Net is designed to operate.  Each time the page loads, or posts back, all the variable are initialized and then the UI controls(text box, check box, etc) are then populated with the information recieved from the post back.  The server variables are not saved at all.  

By pressing Button1, the server creates the text box matrix.  When you press Button2, the server doesn't know if you already created the text box matrix.  That is the nature of the internet, stateless.  

Your best bet would be to rebuild the matrix on postback.  I know that is going to suck to do but that is really the only way you can preserve the state of the page from call to call.

I hope some other people have a better idea...
0
 

Author Comment

by:shams_sa
Comment Utility
Sorry but i'm new in ASP.Net and did not understand your solution. In other words, How to build a matrix on postback ?
0
 
LVL 1

Expert Comment

by:warmach
Comment Utility
Basically, the server does not remember who you are (client browser).  It does not know what it sent you the last time you requested a page or clicked a button...  That is why you are getting the error.  You are trying to use the textbox grid, but the server doesn't remember if you created one.

If you wish, you could save the tb grid in a session variable.  Then when you press Button2, manipulate the grid in the Session variable.  At the end of the code to Button2, call create_grid again to show the new grid....

 public void create_grid(int size)
{
     //Look in session variable for an existing textbox grid
     tb = Session("TextBoxGrid");

     if (tb == null){
         //The grid was not in the Session variable...create a new one
          tb = new TextBox[size+1][];
     }


     ....all your previous code....

     Session("TextBoxGrid") = tb
}


 private void Button2_Click(object sender, System.EventArgs e)
          {
               
               if(tb[3][3].Text.Equals("3")) tb[3][1].Text = "T";
               else tb[3][1].Text = "F";

               create_grid(TextBox1.Text);
          }



Hope this helps....let me know if you need more clarification
0
 

Author Comment

by:shams_sa
Comment Utility
I'm sorry to tell you that this is the first Time i heard of "Session". I tried your code and i faced this problem 'System.Web.UI.Page.Session' denotes a 'property' where a 'method' was expected

Also Can you give Sites where can i found informations about "Session"

I also want to Thank you for your help
0
 

Author Comment

by:shams_sa
Comment Utility
I fix the problem, but it did not work...... :(
the problem was the session["   "] not ("   ")
Also when assign the session back to the TextBox tb I Down Cast the session to (TextBox[][])

if i did something wrong, pls tell me.
0
 
LVL 1

Expert Comment

by:warmach
Comment Utility
Please post the code you tried and tell me exactly what is going wrong.
0
 

Author Comment

by:shams_sa
Comment Utility
This is my code as you requested, but before that i want to ask is there a way that i can save the session thru a submit Button. I tried it but I could not do it. If i can store the session when i click on a button, my problem will be solved Hopefully.

My purpose is to store the Grid and Compare it with A Char[][] Grid with the same size When i click on the Button.

This is my Code:

public class WebForm1 : System.Web.UI.Page
      {
            protected System.Web.UI.WebControls.Button Button1;
            protected System.Web.UI.WebControls.TextBox GSize;
      
            HtmlForm Form;
            protected System.Web.UI.WebControls.Button Button2;
            protected System.Web.UI.WebControls.Button Button3;
         
            TextBox[][] tb; // this is my TextBoxes
         
         
            public void create_grid(int size)
            {
                  
                  tb = (TextBox[][]) Session["TextBoxGrid"];

                  if (tb == null)
                  {
                        //The grid was not in the Session variable...create a new one
                        
                        tb = new TextBox[size+1][];
               
                        for(int i = 0;i<tb.Length;i++)
                              tb[i] = new TextBox[size+1];
                   
                        for(int i=0;i<tb.Length;i++)
                              for(int j=0;j<tb.Length;j++)
                                    tb[i][j] = new TextBox();
                  }

                  for (int i = 1; i<tb.Length; i++)
                        for(int j=1;j<tb.Length;j++)
                        {
                              int left = 25+((j-1)*25);
                              int top = 25+((i-1)*25);
                              tb[i][j].Style.Add("POSITION","absolute");
                              tb[i][j].Style.Add("HEIGHT","25");
                              tb[i][j].Style.Add("WIDTH","25");
                              tb[i][j].Style.Add("LEFT",left.ToString());
                              tb[i][j].Style.Add("TOP",top.ToString());
                              tb[i][j].ID = "textBoxddf"+i+j;
         

                              //////////////////////////////////////  Adding them to the Form ///////////////////////////                                        
                              Form.Controls.Add(tb[i][j]);

                         
                         
                        }
                  //            

                  tb[1][1].Text = "T";
                  tb[2][2].Style.Add("Background","Black");
     
                  tb[2][2].ReadOnly = true;
                  if(tb[1][1].Text == "T")
                        tb[3][3].Text = "F";

                  Session["TextBoxGrid"] = tb;
               

            }
            
            private void Page_Load(object sender, System.EventArgs e)
            {
                  // Put user code to initialize the page here
            }

            #region Web Form Designer generated code
            override protected void OnInit(EventArgs e)
            {
                  //
                  // CODEGEN: This call is required by the ASP.NET Web Form Designer.
                  //
                  InitializeComponent();
                  base.OnInit(e);
            }
            
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {    
                  this.Button1.Click += new System.EventHandler(this.Button1_Click);
                  this.Button2.Click += new System.EventHandler(this.Button2_Click);
                  this.Button3.Click += new System.EventHandler(this.Button3_Click);
                  this.Load += new System.EventHandler(this.Page_Load);
                  Form = (System.Web.UI.HtmlControls.HtmlForm)this.FindControl("Form1");

            }
            #endregion

            private void Button1_Click(object sender, System.EventArgs e)
            {
                  create_grid(int.Parse(GSize.Text));
            }

            private void Button2_Click(object sender, System.EventArgs e)
            {
                  if(tb[3][3].Text.Equals("3")) tb[3][1].Text = "T";
                  else tb[3][1].Text = "F";

                  create_grid(int.Parse(GSize.Text));

            }

            private void Button3_Click(object sender, System.EventArgs e)
            {
                  Session["TextBoxGrid"] = tb;
            }
      }
}
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 1

Expert Comment

by:warmach
Comment Utility
The code dealing with the Session object is correct.  I suspect that there is an error somewhere else.  Did you use IIS Manager to create an IIS applicaiton for this page?
0
 

Author Comment

by:shams_sa
Comment Utility
The problem here is I did not assign the session variable to the TextBox[][] tb in the Button2_click method. Instead of that, i assign the TextBox tb to the session when the page is Unloaded using the following code:

private void Page_UnLoad(object sender, System.EventArgs e)
            {
                  Session["TextBoxGrid"] = tb;
            }

It works fine, but the new problem is when i do changes on the TextBoxs in the aspx page No Effect is happen. The Real content of tb[3][3] for example not change.. is there a way to solve this new problem ?

0
 
LVL 1

Expert Comment

by:warmach
Comment Utility
It looks like each time you call create_grid...this code gets called

              tb[1][1].Text = "T";
               tb[2][2].Style.Add("Background","Black");

               tb[2][2].ReadOnly = true;
               if(tb[1][1].Text == "T")
                    tb[3][3].Text = "F";

This code looks like something that you might only want to do when you create the grid.  If so, put it inside another if...

if (tb == null){
...above code...
}

This way it is only run when the grid is create...
0
 

Author Comment

by:shams_sa
Comment Utility
No this code is for Testing only. The problem is only This code is retrieved from the session, i.e only the values which the program insert. My values are not retrieved from the session
0
 
LVL 1

Expert Comment

by:warmach
Comment Utility
Try my above suggestion and see what happens...
0
 

Author Comment

by:shams_sa
Comment Utility
I tried it, but it did not work also. It seems that you did not understand my new problem.

The values I enter in the Boxes are not stored in the TextBox[][], i dont know why!!!!, even if i do save the session in the page unload method.

Note that Button3 is for Checking the content of a specific cell... it allways give me false becuase the filled cell is not stored.

Also if you want me to send you all my work to take a look at it, tell me.
Thanks again for your help.

Here is my new Code:

public class WebForm1 : System.Web.UI.Page
      {
            protected System.Web.UI.WebControls.Button Button1;
            protected System.Web.UI.WebControls.TextBox GSize;
            System.Threading.Thread thrd;
            HtmlForm Form;
            protected System.Web.UI.WebControls.Button Button2;
            protected System.Web.UI.WebControls.Button Button3;
         
            TextBox[][] tb; // this is my TextBoxes
         
         
            public void create_grid(int size)
            {
                  
                  tb = (TextBox[][]) Session["TextBoxGrid"];

                  if (tb == null)
                  {
                        //The grid was not in the Session variable...create a new one
                        
                        tb = new TextBox[size+1][];
               
                        for(int i = 0;i<tb.Length;i++)
                              tb[i] = new TextBox[size+1];
                   
                        for(int i=0;i<tb.Length;i++)
                              for(int j=0;j<tb.Length;j++)
                                    tb[i][j] = new TextBox();
                  }

                  for (int i = 1; i<tb.Length; i++)
                        for(int j=1;j<tb.Length;j++)
                        {
                              int left = 25+((j-1)*25);
                              int top = 25+((i-1)*25);
                              tb[i][j].Style.Add("POSITION","absolute");
                              tb[i][j].Style.Add("HEIGHT","25");
                              tb[i][j].Style.Add("WIDTH","25");
                              tb[i][j].Style.Add("LEFT",left.ToString());
                              tb[i][j].Style.Add("TOP",top.ToString());
                              tb[i][j].ID = "textBoxddf"+i+j;          

                              //////////////////////////////////////  Adding them to the Form ///////////////////////////                                        
                              Form.Controls.Add(tb[i][j]);

                         
                              
                         
                        }

//                  tb[1][1].Text = "T";
//                  tb[2][2].Style.Add("Background","Black");
//    
//                  tb[2][2].ReadOnly = true;
//                  //            if(tb[1][1].Text == "T")
//                  tb[3][3].Text = "F";


                  Session["TextBoxGrid"] = tb;
               

            }
            
            private void Page_Load(object sender, System.EventArgs e)
            {
                  // Put user code to initialize the page here
            }

            #region Web Form Designer generated code
            override protected void OnInit(EventArgs e)
            {
                  //
                  // CODEGEN: This call is required by the ASP.NET Web Form Designer.
                  //
                  InitializeComponent();
                  base.OnInit(e);
            }
            
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {    
                  this.Button1.Click += new System.EventHandler(this.Button1_Click);
                  this.Button2.Click += new System.EventHandler(this.Button2_Click);
                  this.Button3.Click += new System.EventHandler(this.Button3_Click);
                  this.Load += new System.EventHandler(this.Page_Load);
                  Form = (System.Web.UI.HtmlControls.HtmlForm)this.FindControl("Form1");
                  this.Unload += new System.EventHandler(this.Page_UnLoad);
            }
            #endregion

            private void Button1_Click(object sender, System.EventArgs e)
            {
                  create_grid(int.Parse(GSize.Text));
            }

            private void Button2_Click(object sender, System.EventArgs e)
            {
//            //      tb = (TextBox[][]) Session["TextBoxGrid"];
//                  for(int i=1;i<tb.Length;i++)
//                        for(int j=1;j<tb.Length;j++)
//                              Form.Controls.Add(tb[i][j]);

                  create_grid(int.Parse(GSize.Text));

                  if(tb[3][3].Text.Equals("3")) tb[3][1].Text = "TEST";
                  else tb[3][1].Text = "FTEST";

                  //create_grid(int.Parse(GSize.Text));

            }

            private void Button3_Click(object sender, System.EventArgs e)
            {
                  create_grid(int.Parse(GSize.Text));

                  if(tb[4][4].Text !="") Response.Write("Correct "+tb[4][4].Text);
                  else Response.Write("False "+tb[4][4].Text);
            }
            private void Page_UnLoad(object sender, System.EventArgs e)
            {
                  Session["TextBoxGrid"] = tb;
            }
      }

}
0
 

Author Comment

by:shams_sa
Comment Utility
Thanx for your help warmach, but i solved my problem. I used Denis Bauer's custom placeholder control to automatically do add controls for me-- see http://www.DenisBauer.com. this site was given to me by Paul Wilson.

this control save the state of all the controls.

Regards,


0
 

Accepted Solution

by:
modulo earned 0 total points
Comment Utility
PAQed, with points refunded (125)

modulo
Community Support Moderator
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

One of the pain points with developing AJAX, JavaScript, JQuery, and other client-side behaviors is that JavaScript doesn’t allow for cross domain request for pulling content. For example, JavaScript code on www.johnchapman.name could not pull conte…
Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

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

9 Experts available now in Live!

Get 1:1 Help Now