首页 > 开发 > 综合 > 正文

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

2024-07-21 02:23:27
字体:
来源:转载
供稿:网友
今天真是的,又被界面搞的晕头转向.

为了实现.net window datagrid 的某一行可以根据该行某列的值的内容设定该行颜色的功能.

先贴一个连接,里面有datagrid很多功能扩充的解决方案windows forms 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中取值,"itemtype"为行的名称
string colvalue = this.bindingdataview[rownum]["itemtype"].tostring();
char val = colvalue[0];

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 colexceptiontype = new datagridcoloredtextboxcolumn();
colitemtype.bindingdataview = dtorderitem.defaultview; //将table的view赋值
colitemtype.headertext =“itemtype”;
colitemtype.mappingname = “itemtype“;
colitemtype.width = 90;
colitemtype.nulltext = "";
tablestyle.gridcolumnstyles.add(colitemtype);



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