Object reference not set to an instance of an object.+ array +c#

i cant access checkbox array variable on button click

Page 1 of 1

1 Replies - 4790 Views - Last Post: 18 January 2010 - 07:54 AM Rate Topic: -----

#1 satiss7pwr  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 18-January 10

Object reference not set to an instance of an object.+ array +c#

Posted 18 January 2010 - 05:03 AM

public CheckBox[] cb = null;
int z=0;
protected void Page_Load(object sender, EventArgs e)
	{
		if (!IsPostBack)
		{
		   int count = (int)countcmd.ExecuteScalar();
		   Int32 k = Convert.ToInt32(Session["TZ"]);

			cb = new CheckBox[count - k];

		   OleDbCommand cmd = new OleDbCommand("Select   Member_Name from Member_Master", con);
			dr = cmd.ExecuteReader();
			
			
			while (dr.Read())
			{
			
			 //creating check box 
			  
			  
					cb[z] = new CheckBox();
					cb[z].Text = dr["Member_Name"].ToString();
					Panel2.Controls.Add(cb[z]);
					Panel2.Controls.Add(new LiteralControl("</br>"));
					// if (z == (t - 1)) { Button6.Visible = true; }
					z = z + 1;
			  
			}
		}
	}
protected void Button6_Click(object sender, EventArgs e)
{
	  //proccess to get the value of checked box and insert into database
		cb[tzx] = new CheckBox();
	
		for (int x = 0; x < cb.Length; x++)//ERROR OOCUR HERE
		{
			//cb[x] = new CheckBox();
			if (cb[x].Checked == true)
			{
	
					   //remain code..
			  
			}
		}
		
	}


Is This A Good Question/Topic? 0
  • +

Replies To: Object reference not set to an instance of an object.+ array +c#

#2 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1526
  • View blog
  • Posts: 5,961
  • Joined: 21-March 08

Re: Object reference not set to an instance of an object.+ array +c#

Posted 18 January 2010 - 07:54 AM

1. you should learn to use the CODE tags
:code:

2. This seems to be a common mistake. Remember that ASP.Net runs ALL code outside of event handlers and methods. So this code...

public CheckBox[] cb = null;
int z=0;



is executed on EVERY postback. Therefore, when you click a button, the checkbox array is being set to null.

To persist data across postbacks, you can use the Session.

It seems that you only "create" the checkbox array on the first load of the page, though it's kind of hard to tell since your code isn't formatted.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1