Click here to Skip to main content
Click here to Skip to main content

Using a Radio Button in a GridView

By , 14 Mar 2011
 

Introduction

In this article, I am going to give you a brief explanation regarding how to use a radio button in a GridView. Actually I am going to show how we can delete a row from a GridView by selecting a radio button inside the GridView and by clicking on a Delete button outside the GridView.

image1.gif

Steps invloved

Creating a table for our requirement

USE [Sample]
GO
/****** Object:  Table [dbo].[tblCustomers1]  Script Date: 05/12/2010 16:42:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Customers1](
      [CustomerId] [int] IDENTITY(1,1) NOT NULL,
      [City] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
      [PostalCode] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY] 
GO
SET ANSI_PADDING OFF

Stored Procedure for deleting

USE [Sample]
GO
/****** Object:  StoredProcedure [dbo].[empdel]  Script Date: 05/12/2010 16:43:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[empdel] 
 (
 @CustomerID int
 )
AS
 delete from Customers1 where CustomerID=@CustomerID
 RETURN

Databinding

Now it's time to bind the data to the GridView:

private void BindGrid()
{
    string strQuery = "select CustomerID,City,PostalCode from Customers1";
    DataTable dt = new DataTable();
    con = new SqlConnection(ConfigurationSettings.AppSettings["sqlcon"].ToString());
    SqlDataAdapter sda = new SqlDataAdapter();
    cmd = new SqlCommand(strQuery);
    cmd.CommandType = CommandType.Text;
    cmd.Connection = con;
    try
    {
        con.Open();
        sda.SelectCommand = cmd;
        sda.Fill(dt);
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        con.Close();
        sda.Dispose();
        con.Dispose();
    }
}

In the Button click event, write the following code:

protected void Button1_Click(object sender, EventArgs e)
{
    Label1.Visible = false;
    int Id = 0;
    foreach (GridViewRow row in GridView1.Rows)
    {
        RadioButton rb = (RadioButton)row.FindControl("RadioButton1");
        if (rb.Checked)
        {
            Id =Convert.ToInt32(GridView1.Rows[row.RowIndex].Cells[1].Text);
            con=newSqlConnection(ConfigurationSettings.AppSettings["sqlcon"].ToString());
            cmd = new SqlCommand("uspCustomers1Delete", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@CustomerID", SqlDbType.Int);
            cmd.Parameters["@CustomerID"].Value = Id;
            con.Open();
            cmd.ExecuteNonQuery();
            Label1.Visible = true;
            Label1.Text = "Successfully Deleted"; 
            BindGrid();
        }
    }
}

Now I will show you how to raise an alert if none of the radio buttons get selected and if you click on the Delete button.

Sample screen:

image2.gif

Client-side script

For this, in the Design page, write the JavaScript as follows:

<script type="text/javascript">  
function Validate() {  
     var gv = document.getElementById("<%=GridView1.ClientID%>");  
     var rbs = gv.getElementsByTagName("input");  
     var flag = 0;  
     for (var i = 0; i < rbs.length; i++) {  

         if (rbs[i].type == "radio") {  
             if (rbs[i].checked) {  
                 flag = 1;  
                 break;  
             }  
         }  
     }  
     if (flag == 0) {  
         alert("Select One");  
            return false;  
     }  
     else { 
        var x= confirm("Are you sure you want to delete?");
        if(x==true)
            return true;
        else
        {
            if(document.getElementById("<%=Label1.ClientID%>") != null)
            document.getElementById("<%=Label1.ClientID%>").innerText = "";
            return false;
        }
     }     
}  
</script>

One problem when using radio buttons is all the radio buttons will be selected. So for getting only a single radio button selected, use the following script:

<script type="text/javascript">
     function RadioCheck(rb) {
        var gv = document.getElementById("<%=GridView1.ClientID%>");
        var rbs = gv.getElementsByTagName("input");
        var row = rb.parentNode.parentNode;
        for (var i = 0; i < rbs.length; i++) {
            if (rbs[i].type == "radio") {
                if (rbs[i].checked && rbs[i] != rb) {
                    rbs[i].checked = false;
                    break;
                }
            }
        }
    }    
</script>

Call this script while defining the radio button, like:

<asp:RadioButton ID="RadioButton1" runat="server" onclick="RadioCheck(this);"/>

Code-behind

Finally, call the method below in the page load:

protected void Page_Load(object sender, EventArgs e)
{
    Button1.Attributes.Add("onclick", "javascript:return Validate()");
    Label1.Visible = false;
    if (!IsPostBack)
    {
        BindGrid();
    }
}

That's all!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

demouser743
Software Developer
India India
I am Dorababu, working as a Software engineer. Web development in Asp.Net with C#, WinForms and MS sql server are the experience tools that I have had for the past 3 years. Yet to work on WCF, WPF, Silverlight and other latest ones.
Follow on   Twitter   Google+

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130617.1 | Last Updated 14 Mar 2011
Article Copyright 2011 by demouser743
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid