2009-04-02 30 views
20

¿C# le permite agregar un String a RowHeader en un DataGridView? Si es así, ¿cómo se logra?Agregar texto al encabezado de fila de DataGridView

Estoy escribiendo un formulario de Windows para mostrar los datos de pago del cliente del año hasta el momento.

Los ColumnHeaders muestran enero, febrero, marzo, etc. ... y en lugar de tener una columna en blanco con DateTime.Now.Year me gustaría ponerlo en el RowHeader para que se destaque de los datos de pago reales.

+0

¿Me puede dar detalles sobre lo que está tratando de lograr aquí. El contexto ayudará inmensamente a obtener una respuesta. – Lazarus

+0

Mi objetivo es mostrar datos sobre los pagos de los Clientes durante el año. Encabezados de columna muestro enero, febrero, marzo ... Me gustaría colocar el año en el encabezado de fila de la izquierda para que se destaque entre Pagado, No pagado y No facturado en las Células de tabla normales en en la tabla principal. – Bailz

Respuesta

-1

Sí. En primer lugar, gancho en el evento añadido la columna:

this.dataGridView1.ColumnAdded += new DataGridViewColumnEventHandler(dataGridView1_ColumnAdded); 

Luego, en el controlador de eventos, simplemente anexar el texto que desea:

private void dataGridView1_ColumnAdded(object sender, DataGridViewColumnEventArgs e) 
{ 
    e.Column.HeaderText += additionalHeaderText; 
} 
+0

Ah, esto es para 'DataGridViewRow.HeaderCell'. Por alguna razón, C# tiene problemas para configurar 'HeaderCell.Value'. –

+0

Si coloca este código en el constructor, no funcionará. Mueva el código al evento Load del formulario y debería funcionar bien. – AMissico

+0

-1: la pregunta era sobre la configuración del encabezado de la fila, pero la respuesta muestra cómo configurar el encabezado de la columna (que es trivial). – Oliver

9

Usted no tiene que utilizar el evento RowValidated, eso es solo la que utilicé para una pequeña aplicación de prueba para asegurarme de que esto funcionara, pero esto configurará el texto del encabezado de la fila (no la columna) en el año que especifique.

Probablemente iría mejor en el evento CellFormatting, en realidad.

private void dataGridView_RowValidated(object sender, DataGridViewCellEventArgs e) 
    { 
     DataGridView gridView = sender as DataGridView; 

     if (null != gridView) 
     { 
      gridView.Rows[e.RowIndex].HeaderCell.Value = "2009"; 
     } 
    } 

EDITAR: Aquí está toda la TestForm utilicé, lo más simple posible para demostrar la solución. Asegúrese de que su RowHeadersWidth sea lo suficientemente ancho para mostrar el texto.

#region 

using System.ComponentModel; 
using System.Windows.Forms; 

#endregion 

namespace DataGridViewTest 
{ 
    public class GridTest : Form 
    { 
     /// <summary> 
     /// Required designer variable. 
     /// </summary> 
     private IContainer components; 

     private DataGridView dataGridView1; 
     private DataGridViewTextBoxColumn Month; 

     public GridTest() 
     { 
      InitializeComponent(); 
     } 

     /// <summary> 
     /// Clean up any resources being used. 
     /// </summary> 
     /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> 
     protected override void Dispose(bool disposing) 
     { 
      if (disposing && (components != null)) 
      { 
       components.Dispose(); 
      } 
      base.Dispose(disposing); 
     } 

     private void dataGridView_RowValidated(object sender, DataGridViewCellEventArgs e) 
     { 
      DataGridView gridView = sender as DataGridView; 

      if (null != gridView) 
      { 
       gridView.Rows[e.RowIndex].HeaderCell.Value = "2009"; 
      } 
     } 

     #region Windows Form Designer generated code 

     /// <summary> 
     /// Required method for Designer support - do not modify 
     /// the contents of this method with the code editor. 
     /// </summary> 
     private void InitializeComponent() 
     { 
      this.dataGridView1 = new System.Windows.Forms.DataGridView(); 
      this.Month = new System.Windows.Forms.DataGridViewTextBoxColumn(); 
      ((System.ComponentModel.ISupportInitialize) (this.dataGridView1)).BeginInit(); 
      this.SuspendLayout(); 
      // 
      // dataGridView1 
      // 
      this.dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; 
      this.dataGridView1.ColumnHeadersHeightSizeMode = 
       System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; 
      this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] 
                { 
                 this.Month 
                }); 
      this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill; 
      this.dataGridView1.Location = new System.Drawing.Point(0, 0); 
      this.dataGridView1.Name = "dataGridView1"; 
      this.dataGridView1.RowHeadersWidth = 100; 
      this.dataGridView1.Size = new System.Drawing.Size(745, 532); 
      this.dataGridView1.TabIndex = 0; 
      this.dataGridView1.RowValidated += 
       new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView_RowValidated); 
      // 
      // Month 
      // 
      this.Month.HeaderText = "Month"; 
      this.Month.Name = "Month"; 
      // 
      // Form1 
      // 
      this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); 
      this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; 
      this.ClientSize = new System.Drawing.Size(745, 532); 
      this.Controls.Add(this.dataGridView1); 
      this.Name = "Form1"; 
      this.Text = "Form1"; 
      ((System.ComponentModel.ISupportInitialize) (this.dataGridView1)).EndInit(); 
      this.ResumeLayout(false); 
     } 

     #endregion 
    } 
} 
+0

He intentado esto en los eventos RowValidated y CellFormatting, pero ninguno está agregando texto al RowHeader. – Bailz

+0

¿Cuál es el ancho de RowHeader configurado? –

12
datagridview1.Rows[0].HeaderCell.Value = "Your text"; 

Funciona.

2

sí se puede

DataGridView1.Rows[0].HeaderCell.Value = "my text"; 
21
private void dtgworkingdays_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) 
     { 
      this.FillRecordNo(); 
     } 


private void FillRecordNo() 
     { 
      for (int i = 0; i < this.dtworkingdays.Rows.Count; i++) 
      { 
       this.dtgworkingdays.Rows[i].HeaderCell.Value = (i + 1).ToString(); 
      } 
     } 

Véase también Show row number in row header of a DataGridView.

+0

Buena solución genérica. Convertir el remitente a una vista de cuadrícula de datos y usar eso en lugar de dtworkingdays lo hace aún más genérico. – buckley

+0

Creo que esta es la mejor solución cuando se usan datos de enlace. Los otros métodos no funcionaron para mí. –

+0

¡Esto es trabajo para mí! ¡¡¡Rallar!!! – Elshan

-2

asegúrese de que Enable Column Recording esté marcado.

5

¡es por el ancho de su primera columna (columna de encabezado de filas)! ¡aumente su ancho, entonces puede ver su valor! puede utilizar este comando:

dgv1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders; 

(aviso: primero debe establecer dgv1.RowHeadersVisible = true;)

3

que tenían el mismo problema, pero me di cuenta de que mi datagrid perdió encabezado de las filas después de la propiedad datagrid.visible cambió.

Intente actualizar los encabezados de las filas con el evento Datagrid.visiblechanged.

+0

+1 yup tiene razón, ¿por qué haría eso – PUG

1

creo que debe ser:

dataGridView1.Columns[0].HeaderCell.Value = "my text"; 
0

Aquí es un poco de "golpe de pouce"

Public Class DataGridViewRHEx 
Inherits DataGridView 

Protected Overrides Function CreateRowsInstance() As System.Windows.Forms.DataGridViewRowCollection 
    Dim dgvRowCollec As DataGridViewRowCollection = MyBase.CreateRowsInstance() 
    AddHandler dgvRowCollec.CollectionChanged, AddressOf dvgRCChanged 
    Return dgvRowCollec 
End Function 

Private Sub dvgRCChanged(sender As Object, e As System.ComponentModel.CollectionChangeEventArgs) 
    If e.Action = System.ComponentModel.CollectionChangeAction.Add Then 
     Dim dgvRow As DataGridViewRow = e.Element 
     dgvRow.DefaultHeaderCellType = GetType(DataGridViewRowHeaderCellEx) 
    End If 
End Sub 
End Class 

 

Public Class DataGridViewRowHeaderCellEx 
Inherits DataGridViewRowHeaderCell 

Protected Overrides Sub Paint(graphics As System.Drawing.Graphics, clipBounds As System.Drawing.Rectangle, cellBounds As System.Drawing.Rectangle, rowIndex As Integer, dataGridViewElementState As System.Windows.Forms.DataGridViewElementStates, value As Object, formattedValue As Object, errorText As String, cellStyle As System.Windows.Forms.DataGridViewCellStyle, advancedBorderStyle As System.Windows.Forms.DataGridViewAdvancedBorderStyle, paintParts As System.Windows.Forms.DataGridViewPaintParts) 
    If Not Me.OwningRow.DataBoundItem Is Nothing Then 
     If TypeOf Me.OwningRow.DataBoundItem Is DataRowView Then 

     End If 
    End If 
'HERE YOU CAN USE DATAGRIDROW TAG TO PAINT STRING 

    formattedValue = CStr(Me.DataGridView.Rows(rowIndex).Tag) 
    MyBase.Paint(graphics, clipBounds, cellBounds, rowIndex, dataGridViewElementState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts) 
End Sub 
End Class 
+0

? ¿Alguna posibilidad de que pueda explicar este código, y lo que lo convierte en una posible respuesta a la pregunta planteada? –

2

que tenía el mismo problema (?). No se pudo obtener una columna de encabezado para mostrar los datos del encabezado de fila (un número de fila simple) con mi cuadrícula de datos enlazados. Una vez que moví el código al evento "DataBindingComplete" funcionó.

Disculpa el código extra. Quería proporcionar un ejemplo de trabajo pero no tengo tiempo para cortarlo todo, así que simplemente corta y pega una parte de mi aplicación y arreglala para que funcione para ti. Aquí van:

using System; 
using System.Collections.Generic; 
using System.Data; 
using System.Windows.Forms; 
using System.Windows.Forms.DataVisualization.Charting; 

namespace WindowsFormsApplication3 
{ 
    public partial class Form1 : Form 
    { 
     private List<DataPoint> pts = new List<DataPoint>(); 

     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 
      InsertPoint(10, 20); 
      InsertPoint(12, 40); 
      InsertPoint(16, 60); 
      InsertPoint(20, 77); 
      InsertPoint(92, 80); 

      MakeGrid(); 
     } 

     public void InsertPoint(int parameterValue, int commandValue) 
     { 
      DataPoint pt = new DataPoint(); 
      pt.XValue = commandValue; 
      pt.YValues[0] = parameterValue; 
      pts.Add(pt); 
     } 

     private void MakeGrid() 
     { 
      dgv1.SuspendLayout(); 
      DataTable dt = new DataTable(); 
      dt.Columns.Clear(); 
      dt.Columns.Add("Parameter"); 
      dt.Columns.Add("Command"); 

      //*** Add Data to DataTable 
      for (int i = 0; i <= pts.Count - 1; i++) 
      { 
       dt.Rows.Add(pts[i].XValue, pts[i].YValues[0]); 
      } 
      dgv1.DataSource = dt; 

      //*** Formatting for the grid is performed in event dgv1_DataBindingComplete. 
      //*** If its performed here, the changes appear to get wiped in the grid control. 
     } 

     private void dgv1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) 
     { 
      DataGridViewCellStyle style = new DataGridViewCellStyle(); 
      style.Alignment = DataGridViewContentAlignment.MiddleRight; 

      //*** Add row number to each row 
      foreach (DataGridViewRow row in dgv1.Rows) 
      { 
       row.HeaderCell.Value = (row.Index + 1).ToString(); 
       row.HeaderCell.Style = style; 
       row.Resizable = DataGridViewTriState.False; 
      } 
      dgv1.ClearSelection(); 
      dgv1.CurrentCell = null; 
      dgv1.ResumeLayout(); 
     } 
    } 
} 
1
foreach (DataGridViewRow row in datagrid.Rows) 
         row.HeaderCell.Value = String.Format("{0}", row.Index + 1); 
Cuestiones relacionadas