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);