When we use Office Excel, there are a lot of times when we need to freeze rows or columns. At this point, Excel draws an obvious black line between the frozen rows and the non-frozen areas. Such as:
(Fig. 1)
The DataGridView control under WinForm can also implement similar functions for freezing rows or columns (see: Http://msdn.microsoft.com/zh-cn/library/28e9w2e1 (vs.85). aspx), but, The DataGridView control does not, by default, draw a clear dividing line between frozen columns or rows, so it is difficult for end users to notice that columns are currently in place or that rows are frozen. As shown in: Can you quickly find that column is freeze?
(Fig. 2)
Because of this, if we can make Excel-like effect, we can greatly improve the readability of the data.
In general, if we want to draw more on existing controls, we go to the override OnPaint method and then add our own ownerdraw logic, but there are some difficulties on DataGridView:
1. How to determine the location of the frozen dividing line
2. How to ensure that the dividing line is not plotted on scrollbar
Having studied, we can borrow the Cellpainting method provided by DataGridView. When DataGridView draws each cell, it determines whether the current cell is where the dividing line is, and then draws it. The final results are as follows:
(Fig. 3)
The following is the DataGridView Control extension Source code:
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;
}
private
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;
}
}
|
To implement a frozen column boundary in a DataGridView control