擴展 DataGridView 的功能(一)
grid 控件的重要性無需多說了,但要找一個好用的卻是難上加難
雖然市面上有很多成熟公司的成熟產(chǎn)品, 但那些東西畢竟太貴了,所以還是自己寫比較實在(什么, 破解版?還是算了吧)
自vs2005 以后,vs 系統(tǒng)自帶了一個 DataGridView 控件, 這個控件的功能是很強大的,擴展性也不錯, 所以我們就以它為基礎吧
開始統(tǒng)計需要擴展的功能先:
1.顯示行號
2.加入可以輸入文字的 DataGridViewComboBoxCell
2.可分組折疊
3.合并單元格
4.Undo/Redo的支持
5.其他。。。。。
定義類
/// <summary>
/// 擴展的 DataGridView
/// </summary>
public class DataGridViewEx : DataGridView
{
}
/// 擴展的 DataGridView
/// </summary>
public class DataGridViewEx : DataGridView
{
}
先來一個最簡單的:顯示行號
這里我們用到了一個事件 RowPostPaint, 查看MSDN后可知該事件是在“繪制 DataGridViewRow 后發(fā)生”
DataGridView 在繪制 DataGridViewRow 時沒有處理行號, 那就由 DataGridViewEx 來處理吧
知道了原理,添加行號就很簡單了, DrawString 就OK。
給出主要的代碼實現(xiàn) :
void DataGridViewEx_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
if (showRowHeaderNumbers)
{
string title = (e.RowIndex + 1).ToString();
Brush bru = Brushes.Black;
e.Graphics.DrawString(title, DefaultCellStyle.Font,
bru, e.RowBounds.Location.X + RowHeadersWidth / 2 - 4, e.RowBounds.Location.Y + 4);
}
}
{
if (showRowHeaderNumbers)
{
string title = (e.RowIndex + 1).ToString();
Brush bru = Brushes.Black;
e.Graphics.DrawString(title, DefaultCellStyle.Font,
bru, e.RowBounds.Location.X + RowHeadersWidth / 2 - 4, e.RowBounds.Location.Y + 4);
}
}
完成后的效果:

浙公網(wǎng)安備 33010602011771號