chamara
chamara

Reputation: 12709

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?

Upvotes: 0

Views: 7604

Answers (2)

Vinod
Vinod

Reputation: 4892

Try this:

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

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

Upvotes: 3

chamara
chamara

Reputation: 12709

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

Upvotes: 1

Related Questions