轉帖|其它|編輯:郝浩|2010-10-22 11:40:55.000|閱讀 1186 次
概述:我們在使用Office Excel的時候,有很多時候需要凍結行或者列。這時,Excel會在凍結的行列和非凍結的區(qū)域之間繪制上一條明顯的黑線。本文將介紹在DataGridView控件中如何實現(xiàn)凍結列分界線,希望對大家有幫助。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
我們在使用Office Excel的時候,有很多時候需要凍結行或者列。這時,Excel會在凍結的行列和非凍結的區(qū)域之間繪制上一條明顯的黑線。如下圖:
WinForm下的DataGridView控件也能實現(xiàn)類似的凍結行或者列的功能 ,但是呢,DataGridView控件默認不會在凍結列或者行的分界處繪制一個明顯的分界線,這樣的話,最終用戶很難注意到當前有列或者行是凍結的。如下圖所示:你能很快的找到那一列是Freeze的么?
正是因為如此,我們如果能做出類似Excel的效果,就可以大大提高數(shù)據(jù)的可讀性。
通常,我們如果想在現(xiàn)有的控件上多畫點什么,就會去Override OnPaint方法,然后加入自己的OwnerDraw邏輯,但是呢在DataGridView上有一些困難:
1.如何確定凍結分界線的位置
2.如何保證分界線不會繪制到ScrollBar上
研究了一下,我們可以借用DataGridView提供的CellPainting方法。在DataGridView繪制每一個Cell的時候判斷當前Cell是否是分界線所在的位置,然后進行繪制。最終做出的效果如下圖:
以下是DataGridView控件擴展源代碼:
public class DataGridViewEx : DataGridView
{
protected override void OnCellPainting(DataGridViewCellPaintingEventArgs e)
{
base.OnCellPainting(e);
//
// Paints the Frozen line
//
int lastFreezeColumnIndex = GetDisplayColumnFrozenLineIndex();
int lastFreezeRowIndex = GetDisplayRowFrozenLineIndex();
bool drawRowLine = lastFreezeRowIndex != -1 && lastFreezeRowIndex == e.RowIndex;
bool drawColumLine = lastFreezeColumnIndex != -1 && lastFreezeColumnIndex == e.ColumnIndex;
if (drawRowLine || drawColumLine)
{
e.Paint(e.ClipBounds, e.PaintParts);
if (drawColumLine)
{
e.Graphics.DrawLine(Pens.Black,
e.CellBounds.Right - 1, e.CellBounds.Top,
e.CellBounds.Right - 1, this.ClientRectangle.Bottom);
}
if (drawRowLine)
{
e.Graphics.DrawLine(Pens.Black,
e.CellBounds.Left, e.CellBounds.Bottom - 1,
e.CellBounds.Right, e.CellBounds.Bottom - 1);
}
e.Handled = true;
}
}
private int GetDisplayColumnFrozenLineIndex()
{
int lastFreezeColumnIndex = -1;
for (int i = 0; i < this.ColumnCount; i++)
{
DataGridViewColumn column = this.Columns[i];
if (column.Visible && column.Frozen)
{
lastFreezeColumnIndex = i;
}
else if (!column.Frozen)
{
return lastFreezeColumnIndex;
}
}
return lastFreezeColumnIndex;
}
pivate int GetDisplayRowFrozenLineIndex()
{
int lastFreezeRowIndex = -1;
for (int i = 0; i < this.RowCount; i++)
{
DataGridViewRow row = this.Rows[i];
if (row.Visible && row.Frozen)
{
lastFreezeRowIndex = i;
}
else if (!row.Frozen)
{
return lastFreezeRowIndex;
}
}
return lastFreezeRowIndex;
}
}
本站文章除注明轉載外,均為本站原創(chuàng)或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn
文章轉載自:網(wǎng)絡轉載