其實,在很多時候我們對Excel的使用習慣會影響着我們的一些用戶體驗。那今天要介紹的就是像Excel那樣表格行頭會有序號,如下:
一、實現原理及步驟
其實很簡單,要首先去了解DataGridView中表格的構造;通過前面我們的摸索,我們知道在Column中有HeaderCell,那么反過來,行首,是不是應該也有行表頭單元格HeaderCell呢?
從調研中,我發現在DataGridView中有RowTemplate一個屬性,找到這個屬性我就立馬見到了曙光;再進一步嘗試之后發現了RowTemplate中有HeaderCell屬性,這就是我要尋找的行表頭的單元格樣式,那么原理就是將這個行表頭單元格重寫。
public class DataGridViewRowHeaderCellEx:DataGridViewRowHeaderCell { protected override void Paint( System.Drawing.Graphics graphics, System.Drawing.Rectangle clipBounds, System.Drawing.Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts) { base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, errorText,cellStyle, advancedBorderStyle, paintParts); //graphics.DrawString(rowIndex.ToString(), this.DataGridView.Font, new SolidBrush(Color.Blue),cellBounds); TextRenderer.DrawText(graphics, (rowIndex+1).ToString(), DataGridView.Font, cellBounds, Color.Black); } }
從上面的代碼來看,真的很簡單的實現了RowHeaderCell的重寫了,然后在注冊:public DataGridViewEx() : base() { this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw, true); this.CellFormatterRegister = new DataGridCellFormatter(); this.RowTemplate.HeaderCell = new DataGridViewRowHeaderCellEx(); }可以了,這樣就實現了我們需要的簡單的效果了,不過這只是簡單的實現,以后要增加圖例或者其他要求的話,直接在擴展里面繪制就行了。
二、需要注意的地方
我們先來看兩種效果:
從兩幅圖看來,主要的區別在於在索引文字的顯示位置和對齊方式。圖一時使用graphics.DrawString的,后者是使用TextRenderer來做的,兩種效果有明顯的不同,這就是本次例子要注意的地方;TextRenderer繪制出來的文字通常情況下是按照中間位置並且不會影響到區域的本來的背景等,所以建議在更多的情況下用TextRenderer來繪制文本。
三、演示程序及源碼
演示程序:04[20120505]DataGridViewRowHeaderCellEx@DataGridViewEx.rar
開源項目:http://sourceforge.net/p/datagridviewex/code-0/3/tree/trunk/DataGridViewEx/