Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

c# - How can I create a footer for cell in datagridview

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.

Anyways thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

enter image description here

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;

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";

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;
    }
}

For longer multiline footnotes you can use a bounding Rectangle instead of just the x&y coordinates..


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...