How can I create a footer for cell in datagridview

帅比萌擦擦* 提交于 2019-11-27 16:18:33

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..

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!