c# - datagridview 中的垂直文本

标签 c# .net winforms datagridview vertical-text

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

谢谢

最佳答案

您可以使用标题的自定义单元格绘制来实现您想要的结果。

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

您需要以下代码(比如在初始化组件后的 Form_Load 中)

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

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

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

关于c# - datagridview 中的垂直文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5782674/

相关文章:

c# - Dump() 对象到 JSON pretty-print 字符串

.net - 如何检测双击 Web 浏览器控件?

c# - Socket.EndAccept() 错误 10054

c# - 如何让 IsKeyDown 方法在 C# 中工作

c# - BindingSource 上的 EndEdit 更新 DataTable,但 rowstate 仍未改变

c# - 我应该为创建和更新使用不同的DTO吗? (CRUD)

c# - asp.net datagrid findcontrol 为文本框返回 null

c# - 具有包罗万象的路由的 ASP.NET Web API PUT

c# - Backgroundworker RunWorkerCompleted 事件甚至在完成工作之前就已触发

c# - 在 PDF 查看器中以编程方式启用 'selecting tool'