数据网格视图中的垂直文本 [英] Vertical text in datagridview

查看:20
本文介绍了数据网格视图中的垂直文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以垂直方向显示标题单元格中的文本.我该怎么做?

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.

为了回答您的评论要求将文本与单元格底部对齐的方法,我在代码中添加了评论.希望他们是清楚的.

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.

您需要以下代码(例如在初始化组件后的 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);

接下来你需要类似下面的代码:

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

这篇关于数据网格视图中的垂直文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆