public static CheckBox[] cb = null;
int z=0;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
cb = new CheckBox[count - k];
//Database code.........
while (dr.Read())//read data from access database
{
cb[z] = new CheckBox();
cb[z].Text = dr["Member_Name"].ToString();
Panel2.Controls.Add(cb[z]);
Panel2.Controls.Add(new LiteralControl("&l开发者_开发问答t;/br>"));
z = z + 1;
}
}
}
protected void Button6_Click(object sender, EventArgs e)
{
for (int x = 0; x < cb.Length; x++)//ERROR IS HERE:Object reference not set to an instance of an object.
{
if (cb[x].Checked == true)
{
//processing check boxes
}
}
}
Your array needs to be initialized every time the page is called, not only when the page is loaded the first time.
your check box array is not part of the page view state and will therefor not be initialized for you on postbacks. Clicking the button causes a post back and the cb array being uninitialized.
you could do this instead:
foreach (Control ctrl in Panel2.Controls)
{
CheckBox cb = ctrl as CheckBox;
if (cb != null && cb.Checked)
{
//processing check boxes
}
}
Oliver's answer is correct. All what u need to do is just remove the if condition that checks the IsPostBack property of the page and that's why: When u create a control at runtime and then append it to the structure of the asp page it is rendered every time the page is delivered to the client. So when u create it once the page is requested for the first time it is rendered. If the page is posted back to the server again an object of the control should be created in ordered to be rendered and then its previous state is loaded from the view state of the page (true or false for the Checked property in ur case)
精彩评论