原理:主要通過重畫DataGrid來完成.通過此例也可舉一反三,如 實現自定義行標題,也可用此方法實現.為使代碼具有一定的通用性,特寫了一個較為通用的函數,以便調用.以下是實現步驟,
1.首先定義一個通用的函數,此函數的功能可自定義DataGrid指定索引列的標題文字,標題字體,標題文字顏色,標題背景顏色.
{
if ( ! dg.ColumnHeadersVisible)
{
return ;
}
int colheadheight = 18 ;
int captionheight;
int texty = 6 ;
int nCol =- 1 ;
int colwidth;
int x;
if (dg.RowHeadersVisible)
{
x = dg.RowHeaderWidth;
}
else
{
x = 0 ;
}
if (dg.CaptionVisible)
{
captionheight = 22 ;
}
else
{
captionheight = 0 ;
}
while (nCol < index && x <= dg.Width)
{
nCol = dg.HitTest (x,captionheight + texty).Column ;
x ++ ;
}
int xx = x;
while (nCol == index && xx <= dg.Width)
{
nCol = dg.HitTest (xx,captionheight + texty).Column ;
xx ++ ;
}
colwidth = xx - x - 2 ;
e.Graphics.FillRectangle( new SolidBrush(backColor),x,captionheight + 3 ,colwidth,colheadheight);
StringFormat format1 = new StringFormat();
format1.Trimming = StringTrimming.EllipsisWord;
e.Graphics.DrawString(text,font, new SolidBrush(foreColor), new RectangleF(x,captionheight + texty,colwidth,colheadheight),format1);
}
2.在DataGrid的Paint事件中調用函數從而完成自定義列標題.
this.dataGrid1.Paint += new System.Windows.Forms.PaintEventHandler(this.dataGrid1_Paint);
{
try
{
if (((DataGrid)sender).DataSource != null )
{
if (((DataGrid)sender).VisibleColumnCount > 0 )
{
this .DrawColHead((DataGrid)sender,e, 0 , " 第一列 " , new Font(FontFamily.GenericSansSerif, 10.0F , FontStyle.Bold),Color.Thistle,Color.GreenYellow);
this .DrawColHead((DataGrid)sender,e, 1 , " 第二列 " , new Font(FontFamily.GenericSansSerif, 10.0F , FontStyle.Bold),Color.White,Color.Yellow);
}
}
base .OnPaint(e);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
3.為解決刷新問題,則需要設置雙緩沖,但雙緩沖的設置必須要在控件的構造函數中設置才有效,也就是說必須要自定義控件,這樣一來工程就會很大,考慮到這一點,所以在出現橫向滾動條時加一事件得以解決問題:
this.dataGrid1.Scroll += new System.EventHandler(this.dataGrid1_Scroll);
{
this .dataGrid1.Refresh();
}
注:此文是為先前的一個同事寫的.希望能給他一些幫助,同時也給自已一個實踐的機會.共同進度.