轉(zhuǎn)帖|其它|編輯:郝浩|2010-10-22 11:40:55.000|閱讀 1186 次
概述:我們?cè)谑褂肙ffice Excel的時(shí)候,有很多時(shí)候需要凍結(jié)行或者列。這時(shí),Excel會(huì)在凍結(jié)的行列和非凍結(jié)的區(qū)域之間繪制上一條明顯的黑線。本文將介紹在DataGridView控件中如何實(shí)現(xiàn)凍結(jié)列分界線,希望對(duì)大家有幫助。
# 界面/圖表報(bào)表/文檔/IDE等千款熱門(mén)軟控件火熱銷(xiāo)售中 >>
我們?cè)谑褂肙ffice Excel的時(shí)候,有很多時(shí)候需要凍結(jié)行或者列。這時(shí),Excel會(huì)在凍結(jié)的行列和非凍結(jié)的區(qū)域之間繪制上一條明顯的黑線。如下圖:
WinForm下的DataGridView控件也能實(shí)現(xiàn)類(lèi)似的凍結(jié)行或者列的功能 ,但是呢,DataGridView控件默認(rèn)不會(huì)在凍結(jié)列或者行的分界處繪制一個(gè)明顯的分界線,這樣的話,最終用戶很難注意到當(dāng)前有列或者行是凍結(jié)的。如下圖所示:你能很快的找到那一列是Freeze的么?
正是因?yàn)槿绱耍覀內(nèi)绻茏龀鲱?lèi)似Excel的效果,就可以大大提高數(shù)據(jù)的可讀性。
通常,我們?nèi)绻朐诂F(xiàn)有的控件上多畫(huà)點(diǎn)什么,就會(huì)去Override OnPaint方法,然后加入自己的OwnerDraw邏輯,但是呢在DataGridView上有一些困難:
1.如何確定凍結(jié)分界線的位置
2.如何保證分界線不會(huì)繪制到ScrollBar上
研究了一下,我們可以借用DataGridView提供的CellPainting方法。在DataGridView繪制每一個(gè)Cell的時(shí)候判斷當(dāng)前Cell是否是分界線所在的位置,然后進(jìn)行繪制。最終做出的效果如下圖:
以下是DataGridView控件擴(kuò)展源代碼:
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;
}
}
本站文章除注明轉(zhuǎn)載外,均為本站原創(chuàng)或翻譯。歡迎任何形式的轉(zhuǎn)載,但請(qǐng)務(wù)必注明出處、不得修改原文相關(guān)鏈接,如果存在內(nèi)容上的異議請(qǐng)郵件反饋至chenjj@fc6vip.cn
文章轉(zhuǎn)載自:網(wǎng)絡(luò)轉(zhuǎn)載