由于項目需要, 需要對datagrid的數據行, 按不同的條件以不同的背景色相區別。 由于datagrid中沒有相關的屬性和方法可以直接設置,要完成這個功能還挺費些功夫。在網上搜了半天,也沒找到解決方案。只好自己動手,豐衣足食了,:) 。研究了半天, 終于搞定它了。好東西不敢獨享,特貼出來,希望能給需要的人帶來些幫助。
{
//...
//使用datagridtablestyle 顯示datagrid.
datagridtablestyle tablestyle = new datagridtablestyle();
tablestyle.mappingname = "customers";
int numcols = _dataset.tables["customers"].columns.count;
datagridcellcolortextboxcolumn columntextcolumn ;
for(int i = 0; i < numcols; ++i)
{
columntextcolumn = new datagridcellcolortextboxcolumn();
columntextcolumn.headertext = _dataset.tables["customers"].columns[i].columnname;
columntextcolumn.mappingname = _dataset.tables["customers"].columns[i].columnname;
//為每個單元格建立設置背景色的事件.
columntextcolumn.checkcellcolor += new cellcoloreventhandler(setcolorvalues);
tablestyle.gridcolumnstyles.add(columntextcolumn);
}
datagrid1.tablestyles.clear();
datagrid1.tablestyles.add(tablestyle);
datagrid1.datasource = _dataset.tables["customers"];
}
public void setcolorvalues(object sender, datagridcellcoloreventargs e)
{
//根據條件, 將相關行設置不同的背景色.
//下例為國家(datagrid中第9列)為mexico的行設置為紅色,usa的行設為黃色.
if(convert.tostring(datagrid1[e.row,8]) == "mexico")
e.backcolor = color.red;
else if(convert.tostring(datagrid1[e.row,8]) == "usa")
e.backcolor = color.yellow;
}
public class datagridcellcoloreventargs : eventargs
{
private int _row;
private color _backcolor;
public datagridcellcoloreventargs(int row, color val)
{
_row = row;
_backcolor = val;
}
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 datagridcellcolortextboxcolumn : datagridtextboxcolumn
{
public event cellcoloreventhandler checkcellcolor;
public datagridcellcolortextboxcolumn()
{
}
//繼承datagridtextboxcolumn的pain事件.
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, color.white);
checkcellcolor(this, e);
if(e.backcolor != color.white)
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)
{
base.edit(source, rownum, bounds, readonly, instanttext, cellisvisible);
}
}