How to Get Selected Row Cell Value From The GridView in ASP.Net Web Forms

watch_later 11/24/2019

This article gives an explanation of how to get the selected row cell value from the grid view in asp.net web forms using C#, VB.NET, and Bootstrap 4. Here, I'll explain how to fetch the importance of each cell of the selected row of grid view in asp.net using C# and VB.NET as well as you can also learn how to bind data GridView in asp.net web forms, how to integrate bootstrap in your asp.net web application and how to apply bootstrap classes to asp.net controls.

Get Selected Row Cell Value From The GridView


Many of the developers/programmers who worked or working with asp.net web forms will have at least heard talk about GridView. Still, many developers/programmers who are beginners and just started his/her career in the IT sector they didn't know what is GridView, what is the use of GridView, when and where we can use GridView, how to fetch records from Gridview, how to bind GridView and many other questions are in their mind, Even I got many emails from students and beginners and they requested for post an article about GridView in asp.net web forms with a basic explanation of GridView with a simple example, few of them also requested that explain the easy, better and reliable solution for fetch records from GridView so finally after a long time I gonna write an article about GridView and in this articles, I will explain everything basics of Gridview with a simple example so they can get a clear idea about the GridView.


Requirement 


1) Explain what is GridView and the use of GridView in asp.net web forms.
2) Explain what is bootstrap.
3) How to integrate Bootstrap with the asp.net webform application.
4) Explain how to fetch selected row cell value from GridView in the asp.net webform application with an example.

Implementation 

What is GridView in asp.net web forms?


The GridView is a versatile and data-bound control used for selecting, editing, deleting, and sorting data on a web page and is commonly used in ASP.NET web forms applications.

What is Bootstrap?


Bootstrap is the free, open-source, and most popular front-end development framework or toolkit for the creation of responsive and mobile-first websites.

How to integrate Bootstrap with the asp.net web form application?


To integrate Bootstrap with your ASP.NET webforms application you just have to host and link the CSS and Javascript of the Bootstrap framework with your ASP.NET webforms application or include it from a CDN (Content Delivery Network).

To link CSS and Javascript of the bootstrap framework with your ASP.NET webforms application you have to write the following code between <head> tag as shown in the code below.

Integrate bootstrap CDN with your ASP.NET web forms

<head runat="server">
    <title></title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>

Fetch selected row cell value from GridView in asp.net webform


So, let us start with an example so you can get more idea about the same, here we will take an example of an employee management system where we have a list of employees and we will fetch details of an employee by selecting GridView row and we will display that details in the web form using label control.

First, we have to design a web form as shown on the screen above, so we will write the following HTML markup in the .aspx file.

Employees. aspx

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
<body>
    <div class="container">
        <form id="form1" runat="server">
            <div class="row">
                <div class="col-lg-12">
                    <div class="panel panel-heading">
                        <div class="panel-heading text-center">
                            <h1>Employee Management System</h1>
                        </div>
                    </div>
                </div>
                <div class="col-lg-8">
                    <div class="panel panel-default">
                        <div class="panel-heading">Employee List</div>
                        <div class="panel-body">
                            <asp:GridView ID="grdEmp" CssClass="table table-bordered" runat="server"
                                AutoGenerateColumns="false" OnSelectedIndexChanged="grdEmp_SelectedIndexChanged">
                                <Columns>
                                    <asp:BoundField DataField="EmployeeId" HeaderText="EmployeeId" ItemStyle-Width="100" />
                                    <asp:BoundField DataField="EmployeeName" HeaderText="EmployeeName" ItemStyle-Width="150" />
                                    <asp:BoundField DataField="Department" HeaderText="Department" ItemStyle-Width="150" />
                                    <asp:BoundField DataField="Designation" HeaderText="Designation" ItemStyle-Width="150" />
                                    <asp:BoundField DataField="CompanyName" HeaderText="CompanyName" ItemStyle-Width="150" />
                                    <asp:ButtonField Text="Select" ControlStyle-CssClass="btn btn-primary" CommandName="Select" ItemStyle-Width="50" />
                                </Columns>
                            </asp:GridView>
                        </div>
                    </div>
                </div>
                <div class="col-lg-4">
                    <div class="panel panel-default">
                        <div class="panel-heading">Employee Details</div>
                        <div class="panel-body">
                            <asp:Label ID="lblEmployeeDetails" runat="server"></asp:Label>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</body>
</html>

Explanation


As you can see in the code snippet above, here first we have linked bootstrap CSS and Javascript using CDN links between <head> head tag. In the <body> tag we create a division with the bootstrap class container and within that division tag, we create two grids as you can see in the code above with bootstrap class.col-lg-12 for GridView that contains a list of employees and another division with class .col-lg-8 for display selected row cell value from GridView. Here we also have taken one ButtonField for row selection and fetched the selected row cell value from GridView.

Now, we need to bind GridView for the display list of employees into the web form, for that we will create a simple method that returns a data table with a few dummy entries.

C#

private DataTable GetEmployeeData()
    {
        try
        {
            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[5] { new DataColumn("EmployeeId"), new DataColumn("EmployeeName"), new DataColumn("Department"), new DataColumn("Designation"), new DataColumn("CompanyName") });
            dt.Rows.Add(1001, "Nikunj Satasiya""Computer/IT""Software Engineer""Casepoint LLC.");
            dt.Rows.Add(1002, "Hiren Dobariya""Computer/IT""Software Engineer""Version System Pvt.Ltd.");
            dt.Rows.Add(1003, "Vivek Ghadiya""Sales Department""Sales Executive""Balaji Wafers Pvt.Ltd.");
            dt.Rows.Add(1004, "Pritesh Dudhat""Networking""Network Engineer""Narola Infotech");
            dt.Rows.Add(1005, "Priya Patel""Computer/IT""Software Engineer""Thomson Reuters India Pvt.Ltd.");
            return dt;
        }
        catch (Exception)
        {
            throw;
        }
    }

VB.NET

Private Function GetEmployeeData() As DataTable
        Try
            Dim dt As DataTable = New DataTable
            dt.Columns.AddRange(New DataColumn() {New DataColumn("EmployeeId"), New DataColumn("EmployeeName"), New DataColumn("Department"), New DataColumn("Designation"), New DataColumn("CompanyName")})
            dt.Rows.Add(1001, "Nikunj Satasiya""Computer/IT""Software Engineer""Casepoint LLC.")
            dt.Rows.Add(1002, "Hiren Dobariya""Computer/IT""Software Engineer""Version System Pvt.Ltd.")
            dt.Rows.Add(1003, "Vivek Ghadiya""Sales Department""Sales Executive""Balaji Wafers Pvt.Ltd.")
            dt.Rows.Add(1004, "Pritesh Dudhat""Networking""Network Engineer""Narola Infotech")
            dt.Rows.Add(1005, "Priya Patel""Computer/IT""Software Engineer""Thomson Reuters India Pvt.Ltd.")
            Return dt
        Catch ex As Exception
            Throw
        End Try
 
    End Function
Now, We will bind GridView using the Datasource property of GridView in the page load event.

C#

protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!this.IsPostBack)
            {
                grdEmp.DataSource = GetEmployeeData();
                grdEmp.DataBind();
            }
        }
        catch (Exception)
        {
            throw;
        }
        
    }

VB.NET

Protected Sub Page_Load(sender As Object, e As EventArgsHandles Me.Load
        Try
            If Not Me.IsPostBack Then
                grdEmp.DataSource = GetEmployeeData()
                grdEmp.DataBind()
            End If
        Catch ex As Exception
            Throw
        End Try
    End Sub
To, fetch the selected row cell value from GridView we need to generate the selectedIndexChanged event of the grid view and needs to write the following code in the selectedIndexChanged event of GridView.

selected Index Changed

C#

protected void grdEmp_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            string EmployeeId = grdEmp.SelectedRow.Cells[0].Text;
            string EmployeeName = grdEmp.SelectedRow.Cells[1].Text;
            string Department = grdEmp.SelectedRow.Cells[2].Text;
            string Designation = grdEmp.SelectedRow.Cells[3].Text;
            string CompanyName = grdEmp.SelectedRow.Cells[4].Text;
            lblEmployeeDetails.Text = "<b>EmployeeId:</b> " + EmployeeId + " </br><b>EmployeeName:</b> " + EmployeeName + " </br><b>Department:</b> " + Department + " </br><b>Designation:</b> " + Designation + " </br><b>CompanyName:</b> " + CompanyName;
        }
        catch (Exception)
        {
            throw;
        }
    }

VB.NET

Protected Sub grdEmp_SelectedIndexChanged(sender As Object, e As EventArgs)
        Try
            Dim EmployeeId As String = grdEmp.SelectedRow.Cells(0).Text
            Dim EmployeeName As String = grdEmp.SelectedRow.Cells(1).Text
            Dim Department As String = grdEmp.SelectedRow.Cells(2).Text
            Dim Designation As String = grdEmp.SelectedRow.Cells(3).Text
            Dim CompanyName As String = grdEmp.SelectedRow.Cells(4).Text
            lblEmployeeDetails.Text = "<b>EmployeeId:</b> " & EmployeeId & " </br><b>EmployeeName:</b> " & EmployeeName & " </br><b>Department:</b> " & Department & " </br><b>Designation:</b> " & Designation & " </br><b>CompanyName:</b> " & CompanyName
        Catch ex As Exception
            Throw
        End Try
    End Sub

Explanation


As you can see in the screen above here we have fetched a selected row cell value for each cell from the GridView and stored it in a string variable and finally, we displayed it in a simple variable.

Output

How to Get Selected Row Cell Value From The GridView in ASP.Net Web Forms

Recommended Articles


1) Export All The Excel Sheets to DataSet in C# and VB.NET
2) Export JSON to CSV using JQuery/Javascript and Bootstrap in ASP.NET
3) Error 26: Error Locating Server/Instance Specified in SQL Server 2008
4) PIVOT and UNPIVOT in SQL Server with Example
5) Get Distinct Records From Datatable using LINQ C#

Summary


In this article, we learned about the basics of GridView and Bootstrap 4 in ASP.NET web forms as well as also learned a binding of GridView, fetching the value from GridView cell.

Codingvila provides articles and blogs on web and software development for beginners as well as free Academic projects for final year students in Asp.Net, MVC, C#, Vb.Net, SQL Server, Angular Js, Android, PHP, Java, Python, Desktop Software Application and etc.

Thank you for your valuable time, to read this article, If you like this article, please share this article and post your valuable comments.

Once, you post your comment, we will review your posted comment and publish it. It may take a time around 24 business working hours.

Sometimes I not able to give detailed level explanation for your questions or comments, if you want detailed explanation, your can mansion your contact email id along with your question or you can do select given checkbox "Notify me" the time of write comment. So we can drop mail to you.

If you have any questions regarding this article/blog you can contact us on info.codingvila@gmail.com

sentiment_satisfied Emoticon