How to use RadioButtonList control inside the Gridview in Asp.net?


Introduction: In this post I will explain you how we can use RadioBuuttonlist control inside the Gridview.
Gridview

Description:
I have created a table names APPLICANT_DETAIL.
CANDIDATE_ID
int
CANDIDATE_NAME
varchar(50)
CANDIDATE_SEX
varchar(50)
PREFER_CITY
varchar(50)
JOB_PROFILE
varchar(50)
CANDIDATE_ID is primary key.
Now open the Visual Studio>Go to File>New>Website. Add the Connectionstring in web.config file of website.
<configuration>
       <connectionStrings>
    <add name="connection" connectionString="Data Source=SYS-1F78031ED0A;Initial Catalog=TestBlog;Integrated Security=True"/>
       </connectionStrings>
       <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
</configuration>


After that add new web form to website, drag and drop the Gridview data control from Toolbox. After that add the Template field and ItemTemplate in Gridview as structure mention below:

<asp:GridView ID="grdapplicant" runat="server" AutoGenerateColumns="False"
            DataKeyNames="CANDIDATE_ID" onrowdatabound="grdapplicant_RowDataBound"
            onrowediting="grdapplicant_RowEditing"
            onrowupdating="grdapplicant_RowUpdating"
            onrowcancelingedit="grdapplicant_RowCancelingEdit"
            onrowdeleting="grdapplicant_RowDeleting" onpageindexchanging="grdapplicant_PageIndexChanging"
          
            >
            <Columns>
                <asp:TemplateField HeaderText="Candidate Name">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtcandidtaename" runat="server" Text='<%# Eval("CANDIDATE_NAME") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblcandidtae" runat="server" Text='<%# Eval("CANDIDATE_NAME") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Sex">
                    <EditItemTemplate>
                        <asp:RadioButtonList runat="server" ID="rdlsex">
                        <asp:ListItem>Male</asp:ListItem>
                        <asp:ListItem>Female</asp:ListItem>
                        </asp:RadioButtonList>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblsex" runat="server"
                            Text='<%# Eval("CANDIDATE_SEX") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="City">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtcity" runat="server" Text='<%# Eval("PREFER_CITY") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblcity" runat="server" Text='<%# Eval("PREFER_CITY") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Job Profile">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtjob" runat="server" Text='<%# Eval("JOB_PROFILE") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lbljob" runat="server" Text='<%# Eval("JOB_PROFILE") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:CommandField ShowEditButton="True" />
                <asp:CommandField ShowDeleteButton="True" />
            </Columns>
        </asp:GridView>

Now go to .aspx.cs page.
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

  SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());
    protected void Page_Load(object sender, EventArgs e)
    {
        if (con.State == ConnectionState.Closed)
            con.Open();
        if (!IsPostBack)
        {
            Bindgridview();
        }
    }
    private void Bindgridview()
    {
        DataTable dt = new DataTable();
        try
        {
            SqlDataAdapter adp = new SqlDataAdapter("Select * from APPLICANT_DETAIL", con);

            adp.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                grdapplicant.DataSource = dt;
                grdapplicant.DataBind();
            }
            else
            {
                dt.Rows.Add(dt.NewRow());
                grdapplicant.DataSource = dt;
                grdapplicant.DataBind();
                int columncount = grdapplicant.Rows[0].Cells.Count;
                grdapplicant.Rows[0].Cells.Clear();
                grdapplicant.Rows[0].Cells.Add(new TableCell());
                grdapplicant.Rows[0].Cells[0].ColumnSpan = columncount;
                grdapplicant.Rows[0].Cells[0].Text = "No Records Available";

            }
        }
        catch (Exception ex)
        {
        }
        finally
        {
            dt.Clear();
            dt.Dispose();
            dt = new DataTable();
        }
    }

    protected void grdapplicant_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        DataTable dt = new DataTable();
        try
        {
            if (e.Row.RowType == DataControlRowType.DataRow && grdapplicant.EditIndex == e.Row.RowIndex)
            {
              
                RadioButtonList rblsex = (RadioButtonList)e.Row.FindControl("rdlsex");
                            }
        }
        catch (Exception ex) { }
    }
    protected void grdapplicant_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        try
        {
            int CANDIDATE_ID = Convert.ToInt32(grdapplicant.DataKeys[e.RowIndex].Value.ToString());
            TextBox txtname = (TextBox)grdapplicant.Rows[e.RowIndex].FindControl("txtcandidtaename");
            TextBox txtcity = (TextBox)grdapplicant.Rows[e.RowIndex].FindControl("txtcity");
            TextBox txtjob = (TextBox)grdapplicant.Rows[e.RowIndex].FindControl("txtjob");
            RadioButtonList rblsex = (RadioButtonList)grdapplicant.Rows[e.RowIndex].FindControl("rdlsex");
            string Update = "Update APPLICANT_DETAIL set CANDIDATE_NAME='" + txtname.Text + "', PREFER_CITY='" + txtcity.Text + "',JOB_PROFILE='" + txtjob.Text + "',CANDIDATE_SEX='" + rblsex.SelectedItem.ToString() + "' where CANDIDATE_ID=" + CANDIDATE_ID;
            SqlCommand cmd = new SqlCommand(Update, con);
            cmd.ExecuteNonQuery();
            grdapplicant.EditIndex = -1;
            Bindgridview();
        }
        catch (Exception ex)
        {
        }
    }
    protected void grdapplicant_RowEditing(object sender, GridViewEditEventArgs e)
    {
        grdapplicant.EditIndex = e.NewEditIndex;
        Bindgridview();
    }
    protected void grdapplicant_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        grdapplicant.EditIndex = -1;
        Bindgridview();
    }
    protected void grdapplicant_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        try
        {
            int CANDIDATE_ID = Convert.ToInt32(grdapplicant.DataKeys[e.RowIndex].Value.ToString());
            string Delete = "Delete from APPLICANT_DETAIL where CANDIDATE_ID =" + CANDIDATE_ID;
            SqlCommand cmd = new SqlCommand(Delete, con);
            cmd.ExecuteNonQuery();
            Bindgridview();
        }
        catch (Exception ex)
        {
        }
    }
    protected void grdapplicant_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdapplicant.PageIndex = e.NewPageIndex;
        Bindgridview();
    }

In VB
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("connection").ToString())

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If con.State = ConnectionState.Closed Then
            con.Open()
        End If
        If Not IsPostBack Then
            Bindgridview()
        End If
    End Sub
    Private Sub Bindgridview()
        Dim dt As New DataTable()
        Try
            Dim adp As New SqlDataAdapter("Select * from APPLICANT_DETAIL", con)

            adp.Fill(dt)
            If dt.Rows.Count > 0 Then
                grdapplicant.DataSource = dt
                grdapplicant.DataBind()
            Else
                dt.Rows.Add(dt.NewRow())
                grdapplicant.DataSource = dt
                grdapplicant.DataBind()
                Dim columncount As Integer = grdapplicant.Rows(0).Cells.Count
                grdapplicant.Rows(0).Cells.Clear()
                grdapplicant.Rows(0).Cells.Add(New TableCell())
                grdapplicant.Rows(0).Cells(0).ColumnSpan = columncount

                grdapplicant.Rows(0).Cells(0).Text = "No Records Available"
            End If
        Catch ex As Exception
        Finally
            dt.Clear()
            dt.Dispose()
            dt = New DataTable()
        End Try
    End Sub

    Protected Sub grdapplicant_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
        Dim dt As New DataTable()
        Try
            If e.Row.RowType = DataControlRowType.DataRow AndAlso grdapplicant.EditIndex = e.Row.RowIndex Then

                Dim rblsex As RadioButtonList = DirectCast(e.Row.FindControl("rdlsex"), RadioButtonList)
            End If
        Catch ex As Exception
        End Try
    End Sub
    Protected Sub grdapplicant_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
        Try
            Dim CANDIDATE_ID As Integer = Convert.ToInt32(grdapplicant.DataKeys(e.RowIndex).Value.ToString())
            Dim txtname As TextBox = DirectCast(grdapplicant.Rows(e.RowIndex).FindControl("txtcandidtaename"), TextBox)
            Dim txtcity As TextBox = DirectCast(grdapplicant.Rows(e.RowIndex).FindControl("txtcity"), TextBox)
            Dim txtjob As TextBox = DirectCast(grdapplicant.Rows(e.RowIndex).FindControl("txtjob"), TextBox)
            Dim rblsex As RadioButtonList = DirectCast(grdapplicant.Rows(e.RowIndex).FindControl("rdlsex"), RadioButtonList)
            Dim Update As String = (("Update APPLICANT_DETAIL set CANDIDATE_NAME='" + txtname.Text & "', PREFER_CITY='") + txtcity.Text & "',JOB_PROFILE='") + txtjob.Text & "',CANDIDATE_SEX='" & rblsex.SelectedItem.ToString() & "' where CANDIDATE_ID=" & CANDIDATE_ID
            Dim cmd As New SqlCommand(Update, con)
            cmd.ExecuteNonQuery()
            grdapplicant.EditIndex = -1
            Bindgridview()
        Catch ex As Exception
        End Try
    End Sub
    Protected Sub grdapplicant_RowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
        grdapplicant.EditIndex = e.NewEditIndex
        Bindgridview()
    End Sub
    Protected Sub grdapplicant_RowCancelingEdit(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs)
        grdapplicant.EditIndex = -1
        Bindgridview()
    End Sub
    Protected Sub grdapplicant_RowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs)
        Try
            Dim CANDIDATE_ID As Integer = Convert.ToInt32(grdapplicant.DataKeys(e.RowIndex).Value.ToString())
            Dim Delete As String = "Delete from APPLICANT_DETAIL where CANDIDATE_ID =" & CANDIDATE_ID
            Dim cmd As New SqlCommand(Delete, con)
            cmd.ExecuteNonQuery()
            Bindgridview()
        Catch ex As Exception
        End Try
    End Sub

    Protected Sub grdapplicant_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles grdapplicant.PageIndexChanging
        grdapplicant.PageIndex = e.NewPageIndex
        Bindgridview()
    End Sub

Debug the project and check the result.

Related Articles on Gridview:

Ø  How to bind Gridview using Sqldataadapter, Datatable andQuery in Asp.net

Ø  How to highlight row on mouse hover in Gridview

Ø  How to edit and update Dropdownlist in Gridview datacontrol in Asp.net

Ø  How to Search Records in Gridview in Asp.net

Ø  How to Bind Gridview using Store Procedure, SqlDataAdapterand Datatable in Asp.net

Ø  How to Bind Gridview with Datareader in asp.net

                         
  ØHow to use Fileupload control in Gridview inAsp.net

Is it helpful?

If yes post your comment to admire my work. You can like me on Facebook, Google+, Linkedin and Twitter via hit on Follow us Button and also can get update follow by Email.

Post a Comment

[blogger]

MKRdezign

Contact Form

Name

Email *

Message *

Powered by Blogger.
Javascript DisablePlease Enable Javascript To See All Widget