Using Radio Button in GridView

No.of Views3593
Bookmarked1 times
Downloads 
Votes0
By  Dorababu   On  15 May 2010 03:05:52
Tag : ASP.NET , Grid Controls
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
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

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.

Steps by Steps

The basic design view of your program. 

Image Loading

Grid after Binding datat at run time:

Image Loading

Firing an alert if none of the radio box selected

Image Loading

Delete Confirmation :

Image Loading

Displaying Label :

Image Loading

Sample Code and other

 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

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

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 Button click 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();
        }
    }
}
 

Java script alerts for deletion and firing events :

 <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 using radio button is all the radio buttons will be selected. So for getting only 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 radio button like

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

Finally call the below method in page load

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

 This code will help you the most.Happy Coding.

Sample Project Code

Download Source Files- 3 kb

 
Sign Up to vote for this article
 
About Author
 
Dorababu
Occupation-Software Engineer
Company-Mudiam
Member Type-Fresh
Location-India
Joined date-15 May 2010
Home Page-
Blog Page-
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top