首页 > 开发 > 综合 > 正文

将DataGrid中满足条件的行设为不同的背景色(WinForm).

2024-07-21 02:23:43
字体:
来源:转载
供稿:网友
由于项目需要, 需要对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);
}
}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表