问题描述
我需要创建一个包含两个部分的单元格的DataGridView。一部分是该单元格的内容,例如0、1等值。剩下的部分就是该单元格的页脚,就像word文档的页脚一样,指的是该单元格的序数。
I need to create a DataGridView with cells that have two parts. One part is the content of that cell such as 0, 1 etc value. And the remain part is the footer of that cell, just like a footer of a word document, refers to the ordinal number of that cell.
我无法封装任何图像所以这个问题可能是模棱两可的。
I can not enclose any images so the question may be ambiguous.
在此先谢谢大家。
推荐答案
要创建 DataGridView
单元格具有额外的内容,您需要对 CellPainting
事件进行编码。
To create DataGridView
cells with extra content you need to code the CellPainting
event.
首先,您要设置单元格以为多余的内容留出足够的空间,并按需要布置常规内容。.
First you set up the cells to have enough room for the extra content and layout the normal content as you wish..:
DataGridView DGV = dataGridView1; // quick reference
Font fatFont = new Font("Arial Black", 22f);
DGV .DefaultCellStyle.Font = fatFont;
DGV .RowTemplate.Height = 70;
DGV .DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
接下来,我填写一些内容;我将多余的内容添加到单元格的标签
中。对于具有更多字体等的更复杂的内容,您将需要创建一个类或结构来保存它,也许还可以在 Tags
中。.
Next I fill in some content; I add the extra content to the cells' Tags
. For more complicated things with more fonts etc, you will want to create a class or stucture to hold it, maybe also in the Tags
..
DGV.Rows.Clear();
DGV.Rows.Add(3);
DGV[1, 0].Value = "Na"; DGV[1, 0].Tag = "Natrium";
DGV[1, 1].Value = "Fe"; DGV[1, 1].Tag = "Ferrum";
DGV[1, 2].Value = "Au"; DGV[1, 2].Tag = "Aurum";
以下是对 CellPainting
进行编码的示例事件:
Here is an example of coding the CellPainting
event:
private void dataGridView1_CellPainting(object sender,
DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex < 0) return; // header? nothing to do!
if (e.ColumnIndex == yourAnnotatedColumnIndex )
{
DataGridViewCell cell = dataGridView1[e.ColumnIndex, e.RowIndex];
string footnote = "";
if (cell.Tag != null) footnote = cell.Tag.ToString();
int y = e.CellBounds.Bottom - 15; // pick your font height
e.PaintBackground(e.ClipBounds, true); // show selection? why not..
e.PaintContent(e.ClipBounds); // normal content
using (Font smallFont = new Font("Times", 8f))
e.Graphics.DrawString(footnote, smallFont,
cell.Selected ? Brushes.White : Brushes.Black, e.CellBounds.Left, y);
e.Handled = true;
}
}
对于更长的多行脚注,可以使用边界 Rectangle
而不是x& y坐标。.
For longer multiline footnotes you can use a bounding Rectangle
instead of just the x&y coordinates..
这篇关于如何在datagridview中为单元格创建页脚的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!