<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridCell.aspx.cs" Inherits="GridCell" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowCreated"></asp:GridView> </div> </form> </body> </html>
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Collections.Generic; using System.Drawing; public partial class GridCell : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { List<dataStruct> mylist = new List<dataStruct>(); mylist.Add(new dataStruct(new DateTime(1982, 01, 01), "Bill", 'm')); mylist.Add(new dataStruct(new DateTime(1981, 01, 01), "Philip", 'm')); mylist.Add(new dataStruct(new DateTime(1980, 01, 01), "Susan", 'f')); GridView1.DataSource = mylist; GridView1.DataBind(); } public struct dataStruct { private DateTime birthdate; private string name; private char sex; public DateTime BirthDate { get { return birthdate; } set { birthdate = value; } } public string Name { get { return name; } set { name = value; } } public char Sex { get { return sex; } set { sex = value; } } public dataStruct(DateTime _birthdate, string _name, char _sex) { this.birthdate = _birthdate; this.name = _name; this.sex = _sex; } } private List<int> changeColorOnThisColumn; protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e) { // initialize changeColorOnThisColumn if it has not been initialized yet. if (changeColorOnThisColumn == null) changeColorOnThisColumn = new List<int>(); // If this is the header row if (e.Row.RowIndex == -1) { // initialize a counting variable to keep track of the cell index int index = 0; foreach (TableCell cell in e.Row.Cells) { // if the Column is the column that you want to change the color for, add it to the list of columns if (cell.Text == "BirthDate") changeColorOnThisColumn.Add(index); index++; } } // If this is not the header row else if (e.Row.RowIndex != -1) { dataStruct curStruct = (dataStruct)e.Row.DataItem; if (curStruct.Sex == 'f') e.Row.Cells[0].BackColor = Color.Pink; else e.Row.Cells[0].BackColor = Color.Blue; foreach (int index in changeColorOnThisColumn) { e.Row.Cells[index].BackColor = Color.Beige; } } } }


No comments:
Post a Comment