我有DataGridView
我想为行和列设置标题,如下图所示:
Text1描述列标题的含义和行的Text2。
我的问题是,如果这是可能的,如果可能,如何做到(如何做到这一点(覆盖DataGridView
绘制事件?)或者您可以提供哪些其他替代方案来实现这一目标?我希望它优雅直观。
修改
我最终使用了以下代码:
private void dataGridView_tagretTable_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.ColumnIndex == -1 && e.RowIndex == -1)
{
// Clear current drawing, to repaint when user change header width
e.Graphics.Clear(System.Drawing.Color.White);
string drawString = "Text1";
System.Drawing.Font drawFont = new System.Drawing.Font("Arial", 8);
System.Drawing.SolidBrush drawBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black);
System.Drawing.StringFormat drawFormat = new System.Drawing.StringFormat();
// Measure string
SizeF stringSize = new SizeF();
stringSize = e.Graphics.MeasureString(drawString, drawFont);
// offset from rectangle borders
float offset = 3;
// Set string start point
float x = offset;
float y = e.Graphics.ClipBounds.Height - stringSize.Height - offset;
e.Graphics.DrawString(drawString, drawFont, drawBrush, x, y, drawFormat);
drawString = "Text2";
// Measure string
stringSize = e.Graphics.MeasureString(drawString, drawFont);
// Set string start point
x = e.Graphics.ClipBounds.Width - stringSize.Width - offset;
y = offset;
e.Graphics.DrawString(drawString, drawFont, drawBrush, x, y, drawFormat);
// Draw crossing line
Pen myPen = new Pen(Color.Black);
myPen.Width = 1;
e.Graphics.DrawLine(myPen, new Point(0, 0), new Point(e.ClipBounds.Width, e.ClipBounds.Height));
drawFont.Dispose();
drawBrush.Dispose();
drawFormat.Dispose();
myPen.Dispose();
// Set min row header width
if (dataGridView_tagretTable.RowHeadersWidth < 150)
{
dataGridView_tagretTable.RowHeadersWidth = 150;
}
e.Handled = true;
}
}
答案 0 :(得分:4)
很容易(幸运的是)。订阅CellPainting
事件并查找第-1行和第-1列,然后绘制:
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.ColumnIndex == -1 && e.RowIndex == -1)
{
e.Graphics.FillRectangle(Brushes.Red, e.ClipBounds);
e.Handled = true;
}
}
显然,您需要绘制相关细节,我只是做一个红色矩形。确保将事件标记为Handled = true
,否则控件将再次接管绘画。
有关详细信息,请参阅this MSDN Forums link。
如果您希望执行诸如使该文本一般可编辑的内容,您将希望完全从控件派生而不是使用该事件,覆盖支持方法OnCellPainting
并在那里执行。这样,您还可以展示ColumnHeadersTitle
和RowHeadersTitle
的新属性。