Home > front end >  Gridview: Check only one Checkbox at a time
Gridview: Check only one Checkbox at a time

Time:07-12

Context: I have a gridview with checkboxes on each row. The user is able to select a row by checking a checkbox in order to submit that info and progress through the app.

Question: Is it possible to have it where only one checkbox is able to be checked at a time and when another checkbox is selected, all other checkboxes are unchecked?

Aspx:

<asp:GridView ID="GVSelect" runat="server"
                            AutoGenerateColumns="False" DataKeyNames="ID" AllowPaging="True" BackColor="White" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4" OnPageIndexChanging="GvSelect_PageIndexChanging" DataSourceID="SqlDataSource1" ShowHeaderWhenEmpty="True">
                            <Columns>
                                <asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" ReadOnly="True" Visible="False">
                                    <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Wrap="False" Width="100px" />
                                    <ItemStyle HorizontalAlign="Center" />
                                </asp:BoundField>
                                <asp:BoundField DataField="Column 1" HeaderText="Column 1" SortExpression="Column 1" ReadOnly="True">
                                    <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Wrap="False" Width="100px" />
                                    <ItemStyle HorizontalAlign="Center" />
                                </asp:BoundField>
                                <asp:BoundField DataField="Column 2" HeaderText="Column 2" SortExpression="Column 2" ReadOnly="False" DataFormatString="{0:yyyy/MM/dd}">
                                    <ControlStyle Width="90px" />
                                    <FooterStyle HorizontalAlign="Center" />
                                    <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="100px" />
                                    <ItemStyle HorizontalAlign="Center" Width="90px" Wrap="False" />
                                </asp:BoundField>
                                    <ItemTemplate>
                                        <asp:CheckBox ID="chkSel" runat="server" AutoPostBack="true" OnCheckedChanged="chkSel_CheckedChanged" />
                                    </ItemTemplate>
                                    <ControlStyle Width="50px" />
                                    <FooterStyle Width="75px" />
                                    <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                                    <ItemStyle HorizontalAlign="Center"></ItemStyle>
                                </asp:TemplateField>
                                <asp:CommandField ShowEditButton="True">
                                    <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
                                    <ItemStyle HorizontalAlign="Center" BorderWidth="1px" Height="5px" VerticalAlign="Middle" Width="5px" />
                                </asp:CommandField>
                            </Columns>

aspx.cs:

protected void chkSel_CheckedChanged(object sender, EventArgs e)
        {
            int rowind = ((GridViewRow)(sender as Control).NamingContainer).RowIndex;
            CheckBox cb = (CheckBox)GvSelect.Rows[rowind].FindControl("chkSel");
            if (cb.Checked == true)
            {
                lblOne.Text = GvSelect.Rows[rowind].Cells[1].Text;
                lblTwo.Text = GvSelect.Rows[rowind].Cells[2].Text;
            }
            else
            {
                lblOne.Text = "";
                lblTwo.Text = "";
            }
        }

CodePudding user response:

Depending on how many checkboxes you are going to have it may just be easier to have a list or array of boolean values. Where everytime you check a box you deselect all of the others. This is not the most ideal solution however there is no built in behavior for this that I am aware of so it may be your best option.

Give it a try and let me know how it goes.

CodePudding user response:

You can try to add an event on your checkbox, like :

  cb.CheckedChanged  = (sender, args) =>
                        {
                            if (cb.IsChecked)
                            {
                                lblOne.Text = GvSelect.Rows[rowind].Cells[1].Text;
                                lblTwo.Text = GvSelect.Rows[rowind].Cells[2].Text;
                            }
                            else
                            {
                              // uncheck the others                             
                            }
                        };

enter image description here

Ok, now our check box event, it can be like this:

    protected void chkSelect_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox ckBox = sender as CheckBox;
        bool MustCheck = ckBox.Checked;

        // uncheck all rows

        foreach (GridViewRow gRow in GridView1.Rows)
        {
            CheckBox UnCheck = gRow.FindControl("chkSelect") as CheckBox;
            UnCheck.Checked = false;
        }
        // now set the current check box
        ckBox.Checked = MustCheck;
    }

So, above, code behind - with post back.

But, you can quite easy do this 100% client side - javaScript.

So, drop the code behind, and write quite much what amounts to the SAME code, but this time in JavaScript.

So, remove auto-post back, and the event from the the check box - but now use a client side click, say like this:

                <asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center">
                    <ItemTemplate>
                      <asp:CheckBox ID="chkSelect" runat="server"  
                          onclick="mycheckall(this)"
                          />
                    </ItemTemplate>
                </asp:TemplateField>

and right below the GV, this script:

 <script> 
      function mycheckall(btn) {
          var bolChecked = $(btn).is(':checked')

          // now un check all
          MyTable = $('#GridView1')   // get the grid
          MyCheckBoxs = MyTable.find('input:checkbox')  // get all check boxes in grid
          MyCheckBoxs.each(function () {
              $(this).prop('checked', false)
          })

          // now set our one check box we just clicked on
          $(btn).prop('checked',bolChecked)
      }
 </script>

So, both really do the same logic. but, the 2nd example does not require server side code.

  • Related