小李程式™的专栏

有勇气来改变可以改变的事情,有度量接受不可改变的事情,有智慧来分辨两者的不同。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

                                   

DataGrid中由某列的值设定行的颜色

从网上看到关于DataGrid中由某列的值设定行的颜色的例子感觉非常好;
故记录下来;

关键是在定制的DataGridTextBoxColumn里面添加一个DataView的属性,另外重载Paint() .
在使用DataGridTextBoxColumn的时候,将DataGrid绑定的DataView赋值给它.


public class public class DataGridColoredTextBoxColumn : DataGridTextBoxColumn
{
private System.Data.DataView m_bindDataView;
public DataView BindingDataView
{
get
{
return m_bindDataView;
}
set
{
m_bindDataView = value;
}
}

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)
{
// the idea is to conditionally set the foreBrush and/or backbrush
// depending upon some crireria on the cell value
// Here, we color anything that begins with a letter higher than 'F'
try
{
//从DataView中取值,"primarykeyColumnName"为主键列的名称
string colValue = this.BindingDataView[rowNum]["primarykeyColumnName"].ToString();
string val = colValue;

if( val == "F" ) //如果为 “F”则修改颜色
{
backBrush = new SolidBrush(Color.BlueViolet );
foreBrush = new SolidBrush(Color.White);
}
}
catch(Exception ex)
{
//empty catch
}
finally
{
// make sure the base class gets called to do the drawing with
// the possibly changed brushes
base.Paint(g, bounds, source, rowNum, backBrush, foreBrush, alignToRight);
}
}

}


使用方法;
DataGridColoredTextBoxColumn colType = new DataGridColoredTextBoxColumn();
colType.BindingDataView = ds.Tables[0].DefaultView; //将table的view赋值
colItemType.HeaderText =“primarykeyColumnName”;
colItemType.MappingName = “primarykeyColumnName“;
colItemType.Width = 90;
colItemType.NullText = "";
tablestyle.GridColumnStyles.Add(colType);