c# - 在datagridview中,C# 豎排文本

  显示原文与译文双语对照的内容
89 1

我想在垂直方向顯示標題單元格中的文本。我該怎麼做?

謝謝

时间:原作者:0个回答

96 0

你可以使用自定義單元格繪製來實現標題所需的結果。

在回答你的評論,要求一個方法對齊文本與單元格的底部,我已經經添加了註釋我的代碼。他們很清楚。

你需要以下代碼( 在初始化組件后在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;
 }
}
原作者:
...