0

I am binding data to a gridview in Page_Load and then in the same Page_Load I am adding a column of check boxes which are not part of the databinding.

Then when a button is pressed I want to check to see if any of the boxes are checked. However, when I look for the checkboxes in my button_click method the checkboxes seem to have disappeared entirely.

I am looking for them with

foreach (GridViewRow gvr in GridView1.Rows)
{
   CheckBox cb = (CheckBox)gvr.FindControl("check" + gvr.Cells[2].Text);
   ...
}

I have a hunch they might be getting destroyed on postback but I'm not sure how to make sure this doesnt happen.

Everything in my Page_Load method is contained in a if(!IsPostBack) statement.

some asked for my page_load:

foreach (GridViewRow gvr in GridView1.Rows) {

                TableCell tc = new TableCell();

                CheckBox cb = new CheckBox();

                cb.ID = "check" + gvr.Cells[2].Text;

                tc.Controls.AddAt(0, cb);

                gvr.Cells.AddAt(0, tc);

            }

I think is the relevant part.

3
  • Show us your Page_Load event please. Commented Nov 25, 2012 at 22:40
  • What is in Cells[2]? The text cannot be altered? Commented Nov 25, 2012 at 22:51
  • Have you disabled view state for the page? If yes, mark EnableViewState="true" at least for the checkbox and other controls, of which you want to persist values during postbacks. If no, then post your Page_Load event, and aspx part as well, if you are doing any processing in javascript or jQuery. Commented Nov 26, 2012 at 5:22

1 Answer 1

3

When creating dynamic controls, put the code that creates them (i.e. the CheckBoxes) in the Page_Init and not in the Page_Load.
You should also double-check that the order in which the checkboxes are created and the ids that they receive are the same in each postback.
If for some reason gvr.Cells[2].Text changes between postbacks, you should probably think of a better logic in which you id your checkboxes.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I think this is the answer but one issue. I need to access a gridview which is created in page_load in order to create my new dynamic controls (I need to know how many controls to make).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.