Hi kankon,
Check this example. Now please take its reference and correct your code.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
HTML
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDataBound="OnRowDataBound">
<Columns>
<asp:BoundField DataField="CustomerID" HeaderText="Id"></asp:BoundField>
<asp:BoundField DataField="ContactName" HeaderText="Name"></asp:BoundField>
<asp:BoundField DataField="Country" HeaderText="Country"></asp:BoundField>
</Columns>
</asp:GridView>
Namespaces
C#
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
VB.Net
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.Drawing
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string query = "SELECT CustomerID,ContactName,Country FROM Customers ORDER BY Country";
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
string prevCountry = "";
Random rnd = new Random();
Color color;
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (prevCountry == "" || prevCountry != e.Row.Cells[2].Text.Trim())
{
color = Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), 0);
prevCountry = e.Row.Cells[2].Text.Trim();
}
else
{
prevCountry = e.Row.Cells[2].Text.Trim();
}
e.Row.BackColor = color;
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim query As String = "SELECT CustomerID,ContactName,Country FROM Customers ORDER BY Country"
Dim cmd As SqlCommand = New SqlCommand(query)
Using con As SqlConnection = New SqlConnection(conString)
Using sda As SqlDataAdapter = New SqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Using dt As DataTable = New DataTable()
sda.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
End Using
End Using
End Using
End If
End Sub
Private prevCountry As String = ""
Private rnd As Random = New Random()
Private color As Color
Protected Sub OnRowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
If prevCountry = "" OrElse prevCountry <> e.Row.Cells(2).Text.Trim() Then
color = Color.FromArgb(rnd.Next(0, 256), rnd.Next(0, 256), 0)
prevCountry = e.Row.Cells(2).Text.Trim()
Else
prevCountry = e.Row.Cells(2).Text.Trim()
End If
e.Row.BackColor = color
End If
End Sub
Screenshot