Using Radio Button in GridView

In this article I am going to give you a brief explanation regarding how to use a Radio button in grid view.

Actually I am going to show how we can delete a row from grid view by selecting the radio button inside the grid view and by clicking on delete button outside the grid view.

Sample screen

image1.gif
 
Creating a table for our requirement
  1. USE [Sample]  
  2. GO  
  3. /****** Object:  Table [dbo].[tblCustomers1]    Script Date: 05/12/2010 16:42:17 ******/  
  4. SET ANSI_NULLS ON  
  5. GO  
  6. SET QUOTED_IDENTIFIER ON  
  7. GO  
  8. SET ANSI_PADDING ON  
  9. GO  
  10. CREATE TABLE [dbo].[Customers1](  
  11.       [CustomerId] [int] IDENTITY(1,1) NOT NULL,  
  12.       [City] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,  
  13.       [PostalCode] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL  
  14. ON [PRIMARY]  
  15.   
  16. GO  
  17. SET ANSI_PADDING OFF  
Stored procedure for deleting

  1. USE [Sample]  
  2. GO  
  3. /****** Object:  StoredProcedure [dbo].[empdel]    Script Date: 05/12/2010 16:43:43 ******/  
  4. SET ANSI_NULLS ON  
  5. GO  
  6. SET QUOTED_IDENTIFIER ON  
  7. GO  
  8. CREATE PROCEDURE [dbo].[empdel]   
  9.  (  
  10.  @CustomerID int  
  11.  )  
  12. AS  
  13.  delete from Customers1 where CustomerID=@CustomerID  
  14.  RETURN  

 

Now it's the time to bind the data to grid view

  1. private void BindGrid()  
  2. {  
  3.     string strQuery = "select CustomerID,City,PostalCode from Customers1";  
  4.     DataTable dt = new DataTable();  
  5.     con = new SqlConnection(ConfigurationSettings.AppSettings["sqlcon"].ToString());  
  6.     SqlDataAdapter sda = new SqlDataAdapter();  
  7.     cmd = new SqlCommand(strQuery);  
  8.     cmd.CommandType = CommandType.Text;  
  9.     cmd.Connection = con;  
  10.     try  
  11.     {  
  12.         con.Open();  
  13.         sda.SelectCommand = cmd;  
  14.         sda.Fill(dt);  
  15.         GridView1.DataSource = dt;  
  16.         GridView1.DataBind();  
  17.     }  
  18.     catch (Exception ex)  
  19.     {  
  20.         throw ex;  
  21.     }  
  22.     finally  
  23.     {  
  24.         con.Close();  
  25.         sda.Dispose();  
  26.         con.Dispose();  
  27.     }  
  28. }  
In Button click write the following code
  1. protected void Button1_Click(object sender, EventArgs e)  
  2. {  
  3.     Label1.Visible = false;  
  4.     int Id = 0;  
  5.     foreach (GridViewRow row in GridView1.Rows)  
  6.     {  
  7.         RadioButton rb = (RadioButton)row.FindControl("RadioButton1");  
  8.         if (rb.Checked)  
  9.         {  
  10.             Id =Convert.ToInt32(GridView1.Rows[row.RowIndex].Cells[1].Text);  
  11.             con=newSqlConnection(ConfigurationSettings.AppSettings["sqlcon"].ToString());  
  12.             cmd = new SqlCommand("uspCustomers1Delete", con);  
  13.             cmd.CommandType = CommandType.StoredProcedure;  
  14.             cmd.Parameters.Add("@CustomerID", SqlDbType.Int);  
  15.             cmd.Parameters["@CustomerID"].Value = Id;  
  16.             con.Open();  
  17.             cmd.ExecuteNonQuery();  
  18.             Label1.Visible = true;  
  19.             Label1.Text = "Successfully Deleted";   
  20.             BindGrid();  
  21.         }  
  22.     }  
  23. }  
Now I will show you how to raise an alert if none of the radio buttons get selected and if you click on delete button.

Sample Screen

image2.gif

For this in design page write the javascript as follows

  1. <script type="text/javascript">    
  2.          function Validate() {    
  3.              var gv = document.getElementById("<%=GridView1.ClientID%>");    
  4.              var rbs = gv.getElementsByTagName("input");    
  5.              var flag = 0;    
  6.              for (var i = 0; i < rbs.length; i++) {   
  7.   
  8.                  if (rbs[i].type == "radio") {    
  9.                      if (rbs[i].checked) {    
  10.                          flag = 1;    
  11.                          break;    
  12.                      }    
  13.                  }    
  14.              }    
  15.              if (flag == 0) {    
  16.                  alert("Select One");    
  17.                  return false;    
  18.              }    
  19.              else {   
  20.                  var x= confirm("Are you sure you want to delete?");  
  21.                  if(x==true)  
  22.                     return true;  
  23.                     else  
  24.                     {  
  25.                         if(document.getElementById("<%=Label1.ClientID%>") != null)  
  26.                         document.getElementById("<%=Label1.ClientID%>").innerText = "";  
  27.                         return false;  
  28.                     }  
  29.              }       
  30.          }    
  31. </script>  
One problem using radio button is all the radio buttons will be selected. So for getting only single radio button selected use the following script
  1. <script type="text/javascript">  
  2.      function RadioCheck(rb) {  
  3.         var gv = document.getElementById("<%=GridView1.ClientID%>");  
  4.         var rbs = gv.getElementsByTagName("input");  
  5.         var row = rb.parentNode.parentNode;  
  6.         for (var i = 0; i < rbs.length; i++) {  
  7.             if (rbs[i].type == "radio") {  
  8.                 if (rbs[i].checked && rbs[i] != rb) {  
  9.                     rbs[i].checked = false;  
  10.                     break;  
  11.                 }  
  12.             }  
  13.         }  
  14.     }      
  15. </script>  
Call this script while defining radio button like
  1. <asp:RadioButton ID="RadioButton1" runat="server" onclick="RadioCheck(this);"/>  
Finally call the below method in page load 
  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     Button1.Attributes.Add("onclick""javascript:return Validate()");  
  4.     Label1.Visible = false;  
  5.     if (!IsPostBack)  
  6.     {  
  7.         BindGrid();  
  8.     }  
  9. }  
The code for this is attached. Please go through the code for complete output.

Happy Coding....