Mostrando entradas con la etiqueta Vertical. Mostrar todas las entradas
Mostrando entradas con la etiqueta Vertical. Mostrar todas las entradas

Mostrando un texto vertical en la celda de un DataGridView

Problema: Necesito que el texto de una celda se muestre de manera vertical.
Solución: Se debe controlar el evento CellPainting del DataGridView.

Para entenderlo mejor, pongo un ejemplo a continuación.

Tengo un formulario llamado Form1, el cual contiene un grid llamado DataGridView1.

En el load del formulario tengo el llenado del grid.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
 'Se llenan datos de prueba en el grid
 Dim dt As New DataTable()
 dt.Columns.Add("c1")
 dt.Columns.Add("c2")

 For j As Integer = 0 To 9
  dt.Rows.Add("aaaaaaaaa", "bbbb") 'Son datos cualquiera de prueba
 Next

 Me.DataGridView1.DataSource = dt

 For j As Integer = 0 To 9
  Dim height As Integer = TextRenderer.MeasureText(Me.DataGridView1(0, j).Value.ToString(), _
           Me.DataGridView1.DefaultCellStyle.Font).Width
      Me.DataGridView1.Rows(j).Height = height
 Next

 AddHandler DataGridView1.CellPainting, AddressOf dataGridView1_CellPainting 'Aqui se invoca al evento CellPainting
End Sub

Después se programa la parte del CellPainting.

No se utiliza la que viene por defecto en el Visual. Esto es copiar y pegar.

Private Sub dataGridView1_CellPainting(ByVal sender As Object, ByVal e As DataGridViewCellPaintingEventArgs)
 If e.ColumnIndex = 0 AndAlso e.RowIndex > -1 AndAlso e.Value IsNot Nothing Then
         e.Paint(e.CellBounds, DataGridViewPaintParts.All And Not DataGridViewPaintParts.ContentForeground)

             Dim sf As New StringFormat()

             sf.Alignment = StringAlignment.Center
             sf.LineAlignment = StringAlignment.Center
             sf.FormatFlags = StringFormatFlags.DirectionVertical 'Aqui le indico que sea vertical

             e.Graphics.DrawString(e.Value.ToString(), e.CellStyle.Font, New SolidBrush(e.CellStyle.ForeColor), e.CellBounds, sf)

             e.Handled = True
        End If
End Sub

Nota: Ejemplos e información proporcionada desde está página web: Windows Forms Data Controls and Databinding FAQ