Sunday, November 15, 2009

grid view conditional formatting

http://www.simple-talk.com/content/article.aspx?article=438

//To disp discontinued items in red and the unitsinstoock items less than '0' as blue
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{ if (e.Row.RowType == DataControlRowType.DataRow)
{
//We're only interested in Rows that contain data
//get a reference to the data used to databound the row
DataRowView drv = (DataRowView)e.Row.DataItem;
if (Convert.ToInt32(drv["UnitsInStock"]) == 0)
{
//The current product has 0 items in stock
e.Row.Font.Bold = true; //Make the font bold
e.Row.ForeColor = System.Drawing.Color.Red;
//Set the text color red
if (Convert.ToInt32(drv["UnitsOnOrder"]) > 0)
{
//The current out of stock item has already been ordered
//Make it blue
e.Row.ForeColor = System.Drawing.Color.Blue;
}
}
if ((bool)drv["Discontinued"])
{
//Discontinued product
//Add the image
Image img = new Image();
img.AlternateText = "Discontinued Product";
img.ImageAlign = ImageAlign.AbsMiddle;
img.ImageUrl = "arrow_down.gif";
img.Width = Unit.Pixel(10);
img.Height = Unit.Pixel(11);
e.Row.Cells[0].Controls.Add(img);
//Add the text as a control
e.Row.Cells[0].Controls.Add(new LiteralControl(" " + e.Row.Cells[0].Text));
} }}
-----------------------------------------------------------------------------------
string previousCat = "";
int firstRow = -1;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//We're only interested in Rows that contain data
//get a reference to the data used to databound the row
DataRowView drv = ((DataRowView)e.Row.DataItem);
if (previousCat == drv["CategoryName"].ToString())
{
//If it's the same category as the previous one
//Increment the rowspan
if (GridView1.Rows[firstRow].Cells[0].RowSpan == 0)
GridView1.Rows[firstRow].Cells[0].RowSpan = 2;
else
GridView1.Rows[firstRow].Cells[0].RowSpan += 1;
//Remove the cell
e.Row.Cells.RemoveAt(0);
}
else //It's a new category
{
//Set the vertical alignment to top
e.Row.VerticalAlign = VerticalAlign.Top;
//Maintain the category in memory
previousCat = drv["CategoryName"].ToString();
firstRow = e.Row.RowIndex;
} }}
-------------------------------------------------------------------------------

No comments: