C# gridview checkbox cannot get value(reason and solution)

Lionsure 2020-09-02 Original by the website

A little carelessness may cause the CheckBox in the GridView to fail to get the value in the process of using the GridView. If you don't understand the reason, a small problem may take a long time.

 

Example of C# gridview checkbox cannot get value

Code in the front page:

<asp:GridView ID="gvProduct" runat="server" AutoGenerateColumns="False" AllowPaging="false" CellPadding="0" CellSpacing="0">
               <FooterStyle BackColor="White" ForeColor="#0cc" />
               <Columns>
               <asp:TemplateField>
                       <ItemStyle CssClass="textc" />
                       <ItemTemplate><asp:CheckBox ID="cb" runat="server" /></ItemTemplate>
               </asp:TemplateField>
               <asp:BoundField DataField="id" Visible="false" HeaderText="ID" />
               <asp:HyperLinkField HeaderText="Product name" DataNavigateUrlFields="id" DataNavigateUrlFormatString="addProduct.aspx?id={0}" DataTextField="Name" DataTextFormatString ="{0}" />
               <
asp:BoundField DataField="price" HeaderText="Price" />
               <
asp:BoundField DataField="BrowseNum" HeaderText="Views" />
               </
Columns>
               <
HeaderStyle ForeColor="#000" CssClass="gvHeader" />
       </asp:GridView>
       <div><asp:Button ID="btnDelete" runat="server" Text=" Delete " OnClick="btnDelete_Click" /></div>

 

Code in the codebehind:

protected void Page_Load(object sender, EventArgs e)
       {
               if (!IsPostBack)
                       BindData();
       }

private void BindData)
       {
       }

protected void btnDelete_Click(object sender, EventArgs e)
       {
               for (int i = 0; i < gvProduct.Rows.Count; i++)
               {
                       CheckBox cb = (CheckBox)gvCommon.Rows[i].FindControl("cb");
                       if (cb.Checked == true)
                       {
                       }
               }
       }

If "BindData();" is not placed in "if (!IsPostBack)", the value of "CheckBox" will not be got in "btnDelete_Click(object sender, EventArgs e)".

The reason is: When you click "Delete", "BindData()" is executed again, which causes the "GridView" to be rebound, which changes the state of the "CheckBox", so it appears that the "CheckBox" was originally selected, but the result was not selected. So be sure to put "BindData()" in "if (!IsPostBack)".