public void DataGridCellColor()
{
//.....
private void BindToGrid()
{
//获取数据源
colText = new DataGridColoredTextBoxColumn(1);
colText.HeaderText = "出库单编号";
colText.Width = 120;
colText.MappingName = "out_storageNumber";
colText.TextBox.DoubleClick += new EventHandler(DataGrid_DoubleClick);
tblStyle.GridColumnStyles.Add(colText);
colText.CheckCellColor += new CellColorEventHandler(SetCellColor);
colText = new DataGridColoredTextBoxColumn(2);
colText.HeaderText = "日期";
colText.MappingName = "theDate";
colText.TextBox.DoubleClick += new EventHandler(DataGrid_DoubleClick);
tblStyle.GridColumnStyles.Add(colText);
colText.CheckCellColor += new CellColorEventHandler(SetCellColor);
//...
gatheringGrid.TableStyles.Add(tblStyle);
}
// 判断当前行是否满足条件, 并设置相应的背景色.
public void SetCellColor(object sender, DataGridCellColorEventArgs e)
{
try
{
DateTime dt = (DateTime)gatheringGrid[e.Row,2];
int intAccountSession = 27;
if(!(gatheringGrid[e.Row,3] is DBNull))
intAccountSession = (int)gatheringGrid[e.Row,3];
TimeSpan ts = DateTime.Parse(Global.g_SystemDateTime) - dt;
if(ts.Days >= intAccountSession)
{
e.BackColor = Color.Red;
}
else if(ts.Days >= intAccountSession - AccountWarning)
{
e.BackColor = Color.YellowGreen;
}
}
catch{}
}
}
//定义事件数据
public class DataGridCellColorEventArgs : EventArgs
{
private int _column;
private int _row;
private Color _backcolor;
public DataGridCellColorEventArgs(int row, int col, Color val)
{
_row = row;
_column = col;
_backcolor = val;
}
public int Column
{
get{ return _column;}
set{ _column = value;}
}
public int Row
{
get{ return _row;}
set{ _row = value;}
}
public Color BackColor
{
get{ return _backcolor;}
set{ _backcolor = value;}
}
}
// 设置委托.
public delegate void CellColorEventHandler(object sender, DataGridCellColorEventArgs e);
//继承样式列.
public class DataGridColoredTextBoxColumn : DataGridTextBoxColumn
{
private int _col;
public event CellColorEventHandler CheckCellColor;
public DataGridColoredTextBoxColumn(int column)
{
_col = column;
}
protected override void Paint(System.Drawing.Graphics g, System.Drawing.Rectangle bounds, System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Brush backBrush, System.Drawing.Brush foreBrush, bool alignToRight)
{
if(CheckCellColor != null)
{
//设置当前行的背景色.
DataGridCellColorEventArgs e = new DataGridCellColorEventArgs(rowNum, _col, Color.White);
CheckCellColor(this, e);
backBrush = new SolidBrush(e.BackColor);
}
base.Paint(g, bounds, source, rowNum, backBrush, foreBrush, alignToRight);
}
protected override void Edit(System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Rectangle bounds, bool readOnly, string instantText, bool cellIsVisible)
{
//do nothing
base.Edit(source,rowNum,bounds,readOnly,instantText,cellIsVisible);
}
}