GridView.RowDataBound is an event in GridView controls in ASP.NET. It occurs when a data row is bound to data in the GridView. Below are examples of how to use this even when binding data to the GridView using C# and VB.NET.

First, let’s create a Visual Studio ASP.NET Application C#.
Note: We will show the code for both C# and VB.NET in this tutorial.

Create-aspnet-csharp

Add a GridView Control to the default page.

add-GridView-aspnet-scharp

HTML

<asp:GridView CssClass="Grid" runat="server" id="myGV" AutoGenerateColumns="False"    AlternatingRowStyle-CssClass="alt"
                      PagerStyle-CssClass="Pager" Width="305px" OnRowDataBound="myGV_RowDataBound">
      <Columns>

          <asp:BoundField ControlStyle-Width="200px" HeaderText="Name"  DataField="Name"/>
               <asp:BoundField ControlStyle-Width="200px" HeaderText="Base Salary" DataFormatString="{0:c}"  DataField="Salary"/>

          <asp:TemplateField HeaderText="Salary After 2% Raise" ControlStyle-Width="200px"><ItemTemplate>0</ItemTemplate> </asp:TemplateField>
      </Columns>
   </asp:GridView>

CSS

<style>
    .Grid {background-color: #fff; margin: 5px 1px 10px 0; border: solid 1px #525252; border-collapse:collapse; font-family:Calibri; color: #474747;}
.Grid td {
      padding: 2px;
      border: solid 2px #c0c0c0; }
.Grid th  {
      padding : 3px 3px;
      color: #fff;
      background: #363170 ;
      border-left: solid 1px #474747;
      font-size: 1em; }
.Grid .alt {
      background: #fcfcfc; }
.Grid .Pager {background: #363670 ; }
.Grid .Pager table { margin: 3px 0; }
.Grid .Pager td { border-width: 0; padding: 0 6px; border-left: solid 1px #666; font-weight: bold; color: #fff; line-height: 12px; }  
.Grid .Pager a { color: Gray; text-decoration: none; }
.Grid .Pager a:hover { color: #000; text-decoration: none; }

</style>

Now create a new table Employee in Microsoft SQL Server:

SQL

CREATE TABLE [dbo].[Employee]
(
    [Id] INT NOT NULL PRIMARY KEY, 
    [Name] VARCHAR(50) NULL, 
    [Salary] MONEY NULL
)

Add a few records to that table.

Employee-Data

Now bind the Gridview.

C#

protected void Page_Load(object sender, EventArgs e)
       {
           try
           {
               BindDataGrid();
           }
           catch (Exception ex)
           {
               Response.Write(ex.ToString());
           }
       }

       protected void BindDataGrid()
       {
           string connectionStr = "Data Source=TutorialsPanel-DB\SQLEXPRESS; Initial Catalog=TutorialsPanel;Integrated Security=True;";
           SqlConnection cn = new SqlConnection(connectionStr);
           SqlDataAdapter da = new SqlDataAdapter();
           SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
           DataTable dt = new DataTable();
           cmd.CommandText = "Select ID,Name, Salary from Employee Order by Name ASC";
           da.SelectCommand = cmd;
           da.SelectCommand.Connection = cn;
           da.Fill(dt);
           myGV.DataSource = dt;
           myGV.DataBind();

       }

VB.NET

Protected Sub Page_Load(sender As Object, e As EventArgs)
  Try
    BindDataGrid()
  Catch ex As Exception
    Response.Write(ex.ToString())
  End Try
End Sub
Protected Sub BindDataGrid()
  Dim connectionStr As String = "Data Source=TutorialsPanel-DB\SQLEXPRESS; Initial Catalog=TutorialsPanel;Integrated Security=True;"
  Dim cn As New SqlConnection(connectionStr)
  Dim da As New SqlDataAdapter()
  Dim cmd As SqlCommand = New System.Data.SqlClient.SqlCommand()
  Dim dt As New DataTable()
  cmd.CommandText = "Select ID,Name, Salary from Employee Order by Name ASC"
  da.SelectCommand = cmd
  da.SelectCommand.Connection = cn
  da.Fill(dt)
  myGV.DataSource = dt
  myGV.DataBind()
End Sub

Run the solution

rowdataboundgrid1

RowDataBound Event

Now let’s create the examples for the RowDataBound Event.

Example 1: highlight the row in red if salary is equal or above $10.000

C#

protected void myGV_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (Double.Parse( e.Row.Cells[1].Text , System.Globalization.NumberStyles.Currency)  >= 10000.00)
        {
            e.Row.ForeColor = System.Drawing.Color.Red;
        }
    }
}

VB.NET

Protected Sub myGV_RowDataBound(sender As Object, e As GridViewRowEventArgs)
  If e.Row.RowType = DataControlRowType.DataRow Then
    If [Double].Parse(e.Row.Cells(1).Text, System.Globalization.NumberStyles.Currency) >= 10000.0 Then
      e.Row.ForeColor = System.Drawing.Color.Red
    End If
  End If
End Sub

Run the solution.

rowdataboundgrid2

Example 2:

Bind the column “SAlary After 2% Raise” based on the salary and a 2% raise for each employee.

C#

protected void myGV_RowDataBound(object sender, GridViewRowEventArgs e)
{

    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        double baseSalary = Double.Parse(e.Row.Cells[1].Text, System.Globalization.NumberStyles.Currency);
        e.Row.Cells[2].Text = string.Format("{0:C}", Convert.ToDouble( (baseSalary + (baseSalary * 2 / 100)).ToString()));
 
    }
}

VB.NET

Protected Sub myGV_RowDataBound(sender As Object, e As GridViewRowEventArgs)

  If e.Row.RowType = DataControlRowType.DataRow Then
    Dim baseSalary As Double = [Double].Parse(e.Row.Cells(1).Text, System.Globalization.NumberStyles.Currency)

    e.Row.Cells(2).Text = String.Format("{0:C}", Convert.ToDouble((baseSalary + (baseSalary * 2 / 100)).ToString()))
  End If
End Sub

Run the solution

rowdataboundgrid3

Last modified: March 8, 2019

Comments

Write a Reply or Comment

Your email address will not be published.