Sunday, 27 October 2013

C#- Change Gridview Column Row Color Dynamically Based on Condition in Asp.net

Introduction

Here I will explain how to change gridview column, row back color dynamically based on particular condition in asp.net using c#, vb.net.


To change gridview column background color dynamically we need to write the code like as shown below

C# Code
protected void gvdata_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].CssClass = "gridcss";
e.Row.Cells[2].CssClass = "gridcss";
}
}

aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Convert Gridview Columns as Rows in Asp.net</title>
<style type="text/css">
body
{
font-family:Calibri;
}
.gridcss
{
background:#df5015;
font-weight:bold;
color:White;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="gvdata" runat="server" OnRowDataBound=gvdata_RowDataBound>
</asp:GridView>
</form>
</body>
</html>


C# Code
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridviewData();
}
}
protected void BindGridviewData()
{
DataTable dt = new DataTable();
dt.Columns.Add("UserId"typeof(Int32));
dt.Columns.Add("UserName"typeof(string));
dt.Columns.Add("Education"typeof(string));
dt.Columns.Add("Location"typeof(string));
DataRow dtrow = dt.NewRow();    // Create New Row
dtrow["UserId"] = 1;            //Bind Data to Columns
dtrow["UserName"] = "Vamsi";
dtrow["Education"] = "B.Tech";
dtrow["Location"] = "Chennai";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow();               // Create New Row
dtrow["UserId"] = 2;               //Bind Data to Columns
dtrow["UserName"] = "MadhavSai";
dtrow["Education"] = "MBA";
dtrow["Location"] = "Nagpur";
dt.Rows.Add(dtrow);
gvdata.DataSource = dt;
gvdata.DataBind();
}
protected void gvdata_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].CssClass = "gridcss";
e.Row.Cells[2].CssClass = "gridcss";
}
}



Demo

1 comment:

Receive All Free Updates Via Facebook.