How to Allow User to Check Only One Row at a Time in Grid View

Introduction

 
Most developers use a Grid View to display records. 
 
Allowing the user to select only one row from this Grid View.
 
Here is an example I will show you.
  • Using JavaScript
  • Using server event

Create Table State Master

 
SQL Server part
  1. CREATE TABLE [dbo].[StateMaster](  
  2. [StateID] [int] IDENTITY(1,1) primary key NOT NULL,  
  3. [StateName] [varchar](30) NULL,  
  4. [StateCode] [varchar](50) NULL,  
  5. [RecordStatus] [char](1) NULL,  
 
 
Add Some Records
 
 
Web Forms Part
  • Create an ASP.NET WEBAPPLICATION
  • Add a web form
  • Name it "gridviewexample.aspx"
  • Add a Grid View to that form
  • Inside the Grid View add a column as in:
     
    <Columns></ Columns>
  • Inside the column add a TemplateField as in:
     
    <asp: TemplateField>
  • Inside the TemplateField add an Item template
  • Add a Checkbox control
  1. <asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server">  
  2.             <Columns>  
  3.                 <asp:TemplateField HeaderText ="StateName">  
  4.                     <ItemTemplate>  
  5. <asp:CheckBox ID="CheckBox1" Text='<%# Eval("StateName")%>' AutoPostBack="true"  runat="server" onclick="CheckBoxCheck(this);" />  
  6.                     </ItemTemplate>  
  7.                 </asp:TemplateField>  
  8.             </Columns>  
  9.  </asp:GridView> 
You need to add a connection string above the Page load.
  1. SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Myconstr"].ToString()); 
And add a connection string in Web.config.
 
For making a connection with the database you need to add a connection string to the database; here is an example of that.
 
Just replace here with your database value.
  • Data source
  • Database
  • User id
  • Password
  1. <connectionStrings>  
  2.     <add name="Myconstr" connectionString="data source=SAI-PC; Database=AllSampleCode;  user id=sa; password=Pass$123 ;" providerName="system.data.sqlclient"/>  
  3.   </connectionStrings> 
Binding Grid View on the Page Load event.
  1. protected void Page_Load(object sender, EventArgs e)  
  2.     {  
  3.    
  4.         if (!IsPostBack)  
  5.         {  
  6.             getrecords();  
  7.         }  
  8.    
  9.  } 
Now to create a method for binding records for the Grid View.
  1. private void getrecords()  
  2.         {  
  3.    
  4.      SqlCommand cmd = new SqlCommand("select StateID ,StateName from StateMaster ", con);  
  5.             cmd.CommandType = CommandType.Text;  
  6.             SqlDataAdapter da = new SqlDataAdapter();  
  7.             da.SelectCommand = cmd;  
  8.             DataTable dt = new DataTable();  
  9.             da.Fill(dt);  
  10.             GridView1.DataSource = dt;  
  11.             GridView1.DataBind();  
  12.    
  13.         }  
  14.   
  15. Using JavaScript (Onclick) 
In the head part of the .aspx page add the following JavaScript.
 
To see the details, use the Firefox add-on Firebug to debug it.
  1. <script type="text/javascript">  
  2.         function CheckBoxCheck(rb) {  
  3.             debugger;  
  4.             var gv = document.getElementById("<%=GridView1.ClientID%>");  
  5.             var chk = gv.getElementsByTagName("input");  
  6.             var row = rb.parentNode.parentNode;  
  7.             for (var i = 0; i < chk.length; i++) {  
  8.                 if (chk[i].type == "checkbox") {  
  9.                     if (chk[i].checked && chk[i] != rb) {  
  10.                         chk[i].checked = false;  
  11.                         break;  
  12.                     }  
  13.                 }  
  14.             }  
  15.         }      
  16. </script> 
Using Server event ( Checked Changed Event )
  1. <asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server">  
  2.             <Columns>  
  3.                 <asp:TemplateField HeaderText="StateName">  
  4.                     <ItemTemplate>  
  5.                           
  6.  <asp:CheckBox ID="CheckBox1" Text='<%# Eval("StateName")%>' AutoPostBack="true" runat="server"   OnCheckedChanged="CheckBox1_CheckedChanged" />  
  7.                     </ItemTemplate>  
  8.                 </asp:TemplateField>  
  9.             </Columns>  
  10.         </asp:GridView>  
  11.   
  12. protected void CheckBox1_CheckedChanged(object sender, EventArgs e)  
  13.         {  
  14.    
  15.             CheckBox chk = (CheckBox)sender;  
  16.             GridViewRow gv = (GridViewRow)chk.NamingContainer;  
  17.             int rownumber = gv.RowIndex;  
  18.    
  19.             if (chk.Checked)  
  20.             {  
  21.                 int i;  
  22.                 for (i = 0; i <= GridView1.Rows.Count - 1; i++)  
  23.                 {  
  24.                     if (i != rownumber)  
  25.                     {  
  26.         CheckBox chkcheckbox = ((CheckBox)(GridView1.Rows[i].FindControl("CheckBox1")));  
  27.         chkcheckbox.Checked = false;  
  28.                     }  
  29.                 }  
  30.             }  
  31.    
  32.    
  33.         } 
Final output
 
 
Happy coding.