在datagridview的垂直文本文本、datagridview

2023-09-03 00:30:42 作者:庸俗且无趣

我要显示的标题单元以垂直方向的文本。我该怎么办呢?

I want to show the text in the header cells in vertical orientation. How can I do it?

感谢

推荐答案

可以实现你想要使用自定义单元格的绘画页眉的结果。

You can achieve the result you want using custom cell painting for the header.

在回答您的意见,要求的方式,以配合电池底部的文字,我已经添加评论我的code。他们是希望清晰。

In answer to your comment asking for a way to align the text with the bottom of the cell, I've added comments to my code. They are hopefully clear.

您需要以下code(例如在Form_Load初始化组件后)

You need the following code (say in the Form_Load after initializing components)

dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
dataGridView1.ColumnHeadersHeight = 50;
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader;

// Here we attach an event handler to the cell painting event
dataGridView1.CellPainting += new DataGridViewCellPaintingEventHandler(dataGridView1_CellPainting);

接下来,你需要像下面的code:

Next you need something like the following code:

void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    // check that we are in a header cell!
    if (e.RowIndex == -1 && e.ColumnIndex >= 0)
    {
        e.PaintBackground(e.ClipBounds, true);
        Rectangle rect = this.dataGridView1.GetColumnDisplayRectangle(e.ColumnIndex, true);
        Size titleSize = TextRenderer.MeasureText(e.Value.ToString(), e.CellStyle.Font);
        if (this.dataGridView1.ColumnHeadersHeight < titleSize.Width)
        {
            this.dataGridView1.ColumnHeadersHeight = titleSize.Width;
        }

        e.Graphics.TranslateTransform(0, titleSize.Width);
        e.Graphics.RotateTransform(-90.0F);

        // This is the key line for bottom alignment - we adjust the PointF based on the 
        // ColumnHeadersHeight minus the current text width. ColumnHeadersHeight is the
        // maximum of all the columns since we paint cells twice - though this fact
        // may not be true in all usages!   
        e.Graphics.DrawString(e.Value.ToString(), this.Font, Brushes.Black, new PointF(rect.Y - (dataGridView1.ColumnHeadersHeight - titleSize.Width) , rect.X));

        // The old line for comparison
        //e.Graphics.DrawString(e.Value.ToString(), this.Font, Brushes.Black, new PointF(rect.Y, rect.X));


        e.Graphics.RotateTransform(90.0F);
        e.Graphics.TranslateTransform(0, -titleSize.Width);
        e.Handled = true;
    }
}