CheckBox Checked state inside gridview

I have a simple gridview

            <asp:GridView ID="GridView1" runat="server" DataKeyNames="OriginatorID" AutoGenerateColumns="False"
            AllowPaging="True" OnPageIndexChanging="GridView1_PageIndexChanging" PageSize="5"
            OnPreRender="GridView1_PreRender">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:CheckBox ID="CheckBox1" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="Originator" HeaderText="Originator" />
            </Columns>
        </asp:GridView>

I’m calling following code inside GridView1_PageIndexChanging event

        foreach (GridViewRow item in GridView1.Rows)
        {
            try
            {
                if (item.RowType == DataControlRowType.DataRow)
                {
                    CheckBox chk = (CheckBox)(item.Cells[0].FindControl("CheckBox1"));

                    // chk.checked will access the checkbox state on button click event
                    if (chk.Checked)
                    {
                        //code if checked
                    }
                    else
                    {

                    }
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

problem if I select a checkbox and select the next page on gridview it never execute the code inside

 if (chk.Checked)

even though I have checked the chekBoxes it’s not get their state as checked.

why could this happen?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Try this:

Check Wheather you have put your code for binding data to GridView in

If (!IsPostBack)
{
     //Code for Binding Data to GridView 
}

Method 2

my fault.i haven’t done the following

  if (!Page.IsPostBack)
            {

                Binddata();//Bind data to gridview
            }

previously Binddata() method was not inside

if (!Page.IsPostBack)

which was causing the issue


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x