Quiero mostrar el texto en las celdas del encabezado en orientación vertical. ¿Cómo puedo hacerlo?Texto vertical en datagridview
Gracias
Quiero mostrar el texto en las celdas del encabezado en orientación vertical. ¿Cómo puedo hacerlo?Texto vertical en datagridview
Gracias
Puede obtener el resultado que desee utilizando una pintura de celda personalizada para el encabezado.
En respuesta a su comentario que preguntaba cómo alinear el texto con la parte inferior de la celda, agregué comentarios a mi código. Ellos están esperanzadamente claros.
necesita el código siguiente (digamos en el Form_Load después de componentes de inicialización)
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);
A continuación, tiene algo así como el código siguiente:
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;
}
}
DataGrid d = new DataGrid();
d.Columns[0].HeaderStyle.VerticalAlign = VerticalAlign.Bottom;
Si está buscando gridview entonces caso como este: -
GridView gv = new GridView();
gv.Columns[0].ItemStyle.VerticalAlign = VerticalAlign.Bottom;
Si usted está buscando DataGridView entonces caso como este: - crear un objeto de datagridview.
gv.Columns["ColumnName"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.BottomCenter;
@Diego - lo consiguió .... – TechGiant
@TechGiant: La segunda línea para un DataGridView lanza 2 errores: 'System.Windows.Forms. DataGridViewColumn 'no contiene una definición para' ItemStyle 'y no se pudo encontrar ningún método de extensión' ItemStyle 'que aceptara un primer argumento de tipo' System.Windows.Forms.DataGridViewColumn '(¿falta una directiva using o una referencia de ensamblado) y : El nombre 'VerticalAlign' no existe en el contexto actual – Diego
@Diego - for datagrid veo que he escrito la última línea. Pruebe la última línea que dará su resultado – TechGiant
void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
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);
e.Graphics.DrawString(e.Value.ToString(), this.Font,
Brushes.Orange, new PointF(rect.Y, rect.X));
e.Graphics.RotateTransform(90.0F);
e.Graphics.TranslateTransform(0, -titleSize.Width);
e.Handled = true;
}
}
In addition, you could set the AutoSizeColumnsMode property of the
DataGridView to AllCellsExceptHeader in order to make the DataGridView
compact.
Un procesador más simple y más eficaz
Adjuntar evento ya sea a través del diseñador o con esta línea de código
dataGridView1.CellPainting += new DataGridView1_CellPainting(dataGridView1_CellPainting);
controlador de eventos para dibujar texto girado
private void DataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) {
// Vertical text from column 0, or adjust below, if first column(s) to be skipped
if (e.RowIndex == -1 && e.ColumnIndex >= 0) {
e.PaintBackground(e.CellBounds, true);
e.Graphics.TranslateTransform(e.CellBounds.Left , e.CellBounds.Bottom);
e.Graphics.RotateTransform(270);
e.Graphics.DrawString(e.FormattedValue.ToString(),e.CellStyle.Font,Brushes.Black,5,5);
e.Graphics.ResetTransform();
e.Handled = true;
}
}
Aunque, mi advertencia habitual es cambiar el comportamiento estándar de la vista de tabla de datos, comprueba si es necesario. El control puede ser hecho para hacer muchas cosas, pero a menudo hay efectos secundarios inesperados que pueden hacer que se salgan de la pista. –
¡Gracias! ¿Ahora cómo cambiar este código para alinear el texto en la parte inferior de la celda? – Diego
@Diego He agregado un código que se alinea con la parte inferior de la celda, aunque nuevamente, pruébelo a fondo, ya que utiliza el hecho de que la pintura de celda se dispara dos veces para los encabezados, lo que podría no ser cierto. –