show-notice
hide-notice

Tuesday, 2 July 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#.


Description:
  
Now I will explain how to change gridview column background color dynamically based on particular condition in
asp.net using c#

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


# 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";
}
}



<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>
Now in code behind add the following namespace references

C# Code

using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
After that write the following code in code behind

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"] = "GohilRajni";
dtrow["Education"] = "M.C.A";
dtrow["Location"] = "Gujarat";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow();               // Create New Row
dtrow["UserId"] = 2;               //Bind Data to Columns
dtrow["UserName"] = "Shivam";
dtrow["Education"] = "MBA";
dtrow["Location"] = "Gujarat";
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";
}
}



 
 

SHARE THIS POST   

1 comment :

Design by Gohilinfotech | www.gohilinfotech.blogspot.com