在使用 DataGrid 的時候,我們可能會需要在程式碼裡變動某些 Raws 的底色,在 .NET Framework 中的 DataGrid 中並沒有直接可以調用的方法,所以必需要對 DataGrid 的 Style 進行一些修改,然後覆寫其中的 Paint 事件。下面的範例是在網路上找到的,然後我進行一些簡單的修改,確實可以達到我所要的結果,當 TBK 欄位的值等於 “*” 的時候,變動 DataGrid 中該列的底色。

public class ColoredDataGridTextBoxColumn : DataGridTextBoxColumn
{
public ColoredDataGridTextBoxColumn()
{
}

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)
{
try
{
DataRowView v = (DataRowView)source.Current;
string tbkValue = Convert.ToString(v.DataView.Table.Rows[rowNum][“TBK”]);

// TBK
if (tbkValue == “*”)
{
backBrush = new LinearGradientBrush(bounds,
Color.FromArgb(0, 255, 255),
Color.FromArgb(0, 255, 255),
LinearGradientMode.BackwardDiagonal);
foreBrush = new SolidBrush(Color.Black);
}
}
catch(Exception){ /* empty catch */ }
finally
{
base.Paint(g, bounds, source, rowNum, backBrush,
foreBrush, alignToRight);
}
}
}

[使用方法]

DataGridTableStyle tableStyle = new DataGridTableStyle();
tableStyle.MappingName = “tblItems”;
int numCols = myDS.Tables[“tblItems”].Columns.Count;
ColoredDataGridTextBoxColumn aColumnTextColumn ;
for(int i = 0; i < numCols; ++i)
{
aColumnTextColumn = new ColoredDataGridTextBoxColumn();
aColumnTextColumn.HeaderText = myDS.Tables[0].Columns[i].ColumnName;
aColumnTextColumn.MappingName = myDS.Tables[0].Columns[i].ColumnName;
tableStyle.GridColumnStyles.Add(aColumnTextColumn);
System.Windows.Forms.Application.DoEvents();
}
DGItems.TableStyles.Clear();
DGItems.TableStyles.Add(tableStyle);

最後修改日期: 2004-11-08

作者

留言

撰寫回覆或留言

發佈留言必須填寫的電子郵件地址不會公開。