locked
Retrieving states of checkboxes in gridview RRS feed

  • Question

  • User-1882791315 posted

    I'm facing the problem with retrieving the values of checkboxes within a gridview. The gridview is populated by a database, including the checkbox in column 0:

            <asp:GridView ID="gvDenied" runat="server"  
                DataKeyNames="Id"
                CssClass="table table-hover table-striped table-bordered" GridLines="None" AutoGenerateColumns="False" 
                ShowHeaderWhenEmpty="True" EmptyDataText="Geen objecten beschikbaar"  ShowFooter="False"
                AllowPaging="True" PageSize="15"
                OnPageIndexChanging="gvDenied_PageIndexChanging"
                OnRowCommand="gvDenied_RowCommand" >
                <Columns>
                    <asp:TemplateField HeaderText="Authorisatie:">
                        <ItemTemplate >
                            <input type="checkbox"  OnClick="btnSample_Click" id="Granted" <%# Eval("Granted") %> data-toggle="toggle" data-on="toegestaan" data-off="geblokkeerd" data-onstyle="success" data-size="small" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField DataField="description" HeaderText="Naam" />
                </Columns>
                <SortedAscendingHeaderStyle CssClass="sortasc-header" />
                <SortedDescendingHeaderStyle CssClass="sortdesc-header" />
            </asp:GridView>

    the checkbox is an inputfield,type of checkbox.

    Now I want to store the values back in the database.so I need to iterate through the gridview and gets the check-state of each rows. Unfortunately I'm not able to find the correct way to realize this. I searched on the net and tried several examples, but none of them gives me the correct results

    The reason for using the HTMLInput is that I use the Bootstrap Toggle: https://www.bootstraptoggle.com/#

    Thursday, August 27, 2020 6:13 AM

Answers

  • User1535942433 posted

    Hi pkouwer,

    Accroding to your description and codes,I suggest you could use checkboc control and checkboxchanged event to change the check status.

    More details,you could refer to below codes:

    <link href="https://cdn.jsdelivr.net/gh/gitbrent/bootstrap4-toggle@3.6.1/css/bootstrap4-toggle.min.css" rel="stylesheet">
        <link href="Content/bootstrap.min.css" rel="stylesheet" />
        <script src="Scripts/jquery-3.4.1.min.js"></script>
        <script src="Scripts/bootstrap.min.js"></script>
    <script src="https://cdn.jsdelivr.net/gh/gitbrent/bootstrap4-toggle@3.6.1/js/bootstrap4-toggle.min.js"></script>
        <script>
            $(function () {
                $("input[id*=CheckBox1]").bootstrapToggle();
                $("input[id*=CheckBox1]").change(function () {
                    console.log("Changed" + this.prop("checked"));
                });
            })
        </script>
    
     <asp:GridView ID="gvDenied" runat="server"
                    DataKeyNames="Id"
                    CssClass="table table-hover table-striped table-bordered" GridLines="None" AutoGenerateColumns="False"
                    ShowHeaderWhenEmpty="True" EmptyDataText="Geen objecten beschikbaar" ShowFooter="False"
                    AllowPaging="True" PageSize="15" OnPageIndexChanging="gvDenied_PageIndexChanging" OnRowCommand="gvDenied_RowCommand">
                    <Columns>
                        <asp:TemplateField HeaderText="Authorisatie:">
                            <ItemTemplate>
                                <asp:CheckBox ID="CheckBox1" checked='<%# Eval("Granted") %>'  runat="server"  ClientIDMode="Static" OnCheckedChanged="CheckBox1_CheckedChanged"  AutoPostBack="true"/>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:BoundField DataField="description" HeaderText="Naam" />
                    </Columns>
                    <SortedAscendingHeaderStyle CssClass="sortasc-header" />
                    <SortedDescendingHeaderStyle CssClass="sortdesc-header" />
                </asp:GridView>

    Code_behind:

           protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
            {
                string str, strSql;
                str = System.Configuration.ConfigurationManager.ConnectionStrings["aspnet-TestApplicationWithDatabase-20190820030542"].ConnectionString;
                SqlConnection conn = new SqlConnection(str);
                
    
                GridViewRow row = ((GridViewRow)((CheckBox)sender).NamingContainer);
                int index = row.RowIndex +1;
                CheckBox cb1 = (CheckBox)gvDenied.Rows[index].FindControl("CheckBox1");
                string checkboxstatus="";
                if (cb1.Checked == true)
                {
                    checkboxstatus = "true";
                    strSql = "UPDATE GCH  SET Granted = @status  WHERE Id = '" + index + "'";
                    using (SqlConnection con = new SqlConnection(str))
                    {
                        using (SqlCommand cmd = new SqlCommand(strSql, con))
                        {
                            cmd.Parameters.AddWithValue("@status", checkboxstatus);
                            con.Open();
                            cmd.ExecuteNonQuery();
                            con.Close();
                        }
                    }
                    //BindGrid();
                    bind();
                }
    
                else if (cb1.Checked == false)
                {
                    checkboxstatus = "true";
                    strSql = "UPDATE GCH  SET Granted = @status  WHERE Id = '" + index + "'";
                    using (SqlConnection con = new SqlConnection(str))
                    {
                        using (SqlCommand cmd = new SqlCommand(strSql, con))
                        {
                            cmd.Parameters.AddWithValue("@status", checkboxstatus);
                            con.Open();
                            cmd.ExecuteNonQuery();
                            con.Close();
                        }
                    }
                    //BindGrid();
                    bind();
                }
            }

    Best regards,

    Yijing Sun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 27, 2020 9:58 AM

All replies

  • User-18289217 posted

    You need to add runat="server" attribute in order to find the control on server-side

    Thursday, August 27, 2020 6:52 AM
  • User-1882791315 posted

    When I add this to the input-control, a message appears: The server tag is not well formed.

    On the gridview it's already there.

    Thursday, August 27, 2020 8:16 AM
  • User1535942433 posted

    Hi pkouwer,

    Accroding to your description and codes,I suggest you could use checkboc control and checkboxchanged event to change the check status.

    More details,you could refer to below codes:

    <link href="https://cdn.jsdelivr.net/gh/gitbrent/bootstrap4-toggle@3.6.1/css/bootstrap4-toggle.min.css" rel="stylesheet">
        <link href="Content/bootstrap.min.css" rel="stylesheet" />
        <script src="Scripts/jquery-3.4.1.min.js"></script>
        <script src="Scripts/bootstrap.min.js"></script>
    <script src="https://cdn.jsdelivr.net/gh/gitbrent/bootstrap4-toggle@3.6.1/js/bootstrap4-toggle.min.js"></script>
        <script>
            $(function () {
                $("input[id*=CheckBox1]").bootstrapToggle();
                $("input[id*=CheckBox1]").change(function () {
                    console.log("Changed" + this.prop("checked"));
                });
            })
        </script>
    
     <asp:GridView ID="gvDenied" runat="server"
                    DataKeyNames="Id"
                    CssClass="table table-hover table-striped table-bordered" GridLines="None" AutoGenerateColumns="False"
                    ShowHeaderWhenEmpty="True" EmptyDataText="Geen objecten beschikbaar" ShowFooter="False"
                    AllowPaging="True" PageSize="15" OnPageIndexChanging="gvDenied_PageIndexChanging" OnRowCommand="gvDenied_RowCommand">
                    <Columns>
                        <asp:TemplateField HeaderText="Authorisatie:">
                            <ItemTemplate>
                                <asp:CheckBox ID="CheckBox1" checked='<%# Eval("Granted") %>'  runat="server"  ClientIDMode="Static" OnCheckedChanged="CheckBox1_CheckedChanged"  AutoPostBack="true"/>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:BoundField DataField="description" HeaderText="Naam" />
                    </Columns>
                    <SortedAscendingHeaderStyle CssClass="sortasc-header" />
                    <SortedDescendingHeaderStyle CssClass="sortdesc-header" />
                </asp:GridView>

    Code_behind:

           protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
            {
                string str, strSql;
                str = System.Configuration.ConfigurationManager.ConnectionStrings["aspnet-TestApplicationWithDatabase-20190820030542"].ConnectionString;
                SqlConnection conn = new SqlConnection(str);
                
    
                GridViewRow row = ((GridViewRow)((CheckBox)sender).NamingContainer);
                int index = row.RowIndex +1;
                CheckBox cb1 = (CheckBox)gvDenied.Rows[index].FindControl("CheckBox1");
                string checkboxstatus="";
                if (cb1.Checked == true)
                {
                    checkboxstatus = "true";
                    strSql = "UPDATE GCH  SET Granted = @status  WHERE Id = '" + index + "'";
                    using (SqlConnection con = new SqlConnection(str))
                    {
                        using (SqlCommand cmd = new SqlCommand(strSql, con))
                        {
                            cmd.Parameters.AddWithValue("@status", checkboxstatus);
                            con.Open();
                            cmd.ExecuteNonQuery();
                            con.Close();
                        }
                    }
                    //BindGrid();
                    bind();
                }
    
                else if (cb1.Checked == false)
                {
                    checkboxstatus = "true";
                    strSql = "UPDATE GCH  SET Granted = @status  WHERE Id = '" + index + "'";
                    using (SqlConnection con = new SqlConnection(str))
                    {
                        using (SqlCommand cmd = new SqlCommand(strSql, con))
                        {
                            cmd.Parameters.AddWithValue("@status", checkboxstatus);
                            con.Open();
                            cmd.ExecuteNonQuery();
                            con.Close();
                        }
                    }
                    //BindGrid();
                    bind();
                }
            }

    Best regards,

    Yijing Sun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 27, 2020 9:58 AM
  • User-1882791315 posted

    Thanks Yijing Sun,

    this really saved my day !

    Thursday, August 27, 2020 6:16 PM