skip to Main Content

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 = "";
            }
        }

3

Answers


  1. 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.

    Login or Signup to reply.
  2. 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                             
                                }
                            };
    

    https://learn.microsoft.com/fr-fr/dotnet/api/system.web.ui.webcontrols.checkbox.oncheckedchanged?view=netframework-4.8

    Login or Signup to reply.
  3. Ok, you have two ways to do this.

    You can use server side code – that will cause a post-back. Often not the end of the world, but do keep this in mind.

    So, say with this grid view:

    <asp:GridView ID="GridView1" runat="server" CssClass="table"
     AutoGenerateColumns="false" width="45%" DataKeyNames="ID"  >
                <Columns>
                    <asp:BoundField DataField="FirstName" HeaderText="FirstName"  />
                    <asp:BoundField DataField="LastName" HeaderText="LastName"    />
                    <asp:BoundField DataField="HotelName" HeaderText="Hotel Name"    />
                    <asp:BoundField DataField="Description" HeaderText="Description" ItemStyle-Width="270" />
                    <asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center">
                        <ItemTemplate>
                          <asp:CheckBox ID="chkSelect" runat="server"  AutoPostBack="true" 
                              OnCheckedChanged="chkSelect_CheckedChanged"
                              />
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
    

    Note how we drop in a simple plain jane check box. And note the auto post back, and the event stub.

    So, to load the grid, say this:

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                LoadGrid();
        }
    
        void LoadGrid()
        {
            DataTable rstData = MyRst("SELECT * FROM tblHotelsA ORDER BY HotelName");
            GridView1.DataSource = rstData;
            GridView1.DataBind();
    
        }
    
        public DataTable MyRst(string strSQL)
        {
            DataTable rstData = new DataTable();
            using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
            {
                using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
                {
                    cmdSQL.Connection.Open();
                    rstData.Load(cmdSQL.ExecuteReader());
                }
            }
            return rstData;
        }
    

    And we now have this:

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search