C# 向DataGridView行标题添加文本

C# 向DataGridView行标题添加文本,c#,.net,winforms,datagridview,C#,.net,Winforms,Datagridview,C#是否允许向DataGridView中的行标题添加字符串?如果是,它是如何实现的 我正在写一个Windows窗体来显示今年迄今为止的客户付款数据 列标题显示一月、二月、三月等。。。我不想在DateTime.Now.Year上留一个空白栏,我想把它放在行标题中,使它从实际的付款数据中脱颖而出。是的。首先,钩住添加的事件列: this.dataGridView1.ColumnAdded += new DataGridViewColumnEventHandler(dataGridView1_Colu

C#是否允许向DataGridView中的行标题添加字符串?如果是,它是如何实现的

我正在写一个Windows窗体来显示今年迄今为止的客户付款数据


列标题显示一月、二月、三月等。。。我不想在DateTime.Now.Year上留一个空白栏,我想把它放在行标题中,使它从实际的付款数据中脱颖而出。

是的。首先,钩住添加的事件列:

this.dataGridView1.ColumnAdded += new DataGridViewColumnEventHandler(dataGridView1_ColumnAdded);
然后,在事件处理程序中,只需附加您想要的文本:

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

您不必使用RowValidated事件,这只是我在一个小测试应用程序中使用的一个事件,以确保其工作正常,但这会将行(而不是列)标题文本设置为您指定的任何年份

实际上,在CellFormatting事件中可能会更好

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

        if (null != gridView)
        {
            gridView.Rows[e.RowIndex].HeaderCell.Value = "2009";
        }
    }
编辑:下面是我使用的整个测试表单,尽可能简单地演示解决方案。确保RowHeadersWidth足够宽以显示文本

#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
    }
}
#地区
使用系统组件模型;
使用System.Windows.Forms;
#端区
命名空间DataGridViewTest
{
公共类GridTest:表单
{
/// 
///必需的设计器变量。
/// 
私人IContainer组件;
私有DataGridView dataGridView1;
私有DataGridViewTextBoxColumn月;
公共网格测试()
{
初始化组件();
}
/// 
///清理所有正在使用的资源。
/// 
///如果应释放托管资源,则为true;否则为false。
受保护的覆盖无效处置(布尔处置)
{
if(处理和(组件!=null))
{
组件。Dispose();
}
基地。处置(处置);
}
私有void dataGridView_RowValidated(对象发送方,DataGridViewCellEventArgs e)
{
DataGridView gridView=发送方为DataGridView;
如果(null!=gridView)
{
gridView.Rows[e.RowIndex].HeaderCell.Value=“2009”;
}
}
#区域Windows窗体设计器生成的代码
/// 
///设计器支持所需的方法-不修改
///此方法的内容与代码编辑器一起使用。
/// 
私有void InitializeComponent()
{
this.dataGridView1=new System.Windows.Forms.DataGridView();
this.Month=new System.Windows.Forms.DataGridViewTextBoxColumn();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
这个.SuspendLayout();
// 
//dataGridView1
// 
this.dataGridView1.AutoSizeColumnsMode=System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
this.dataGridView1.ColumnHeadersWeightSizeMode=
System.Windows.Forms.DataGridViewColumnHeadersWeightSizeMode.AutoSize;
this.dataGridView1.Columns.AddRange(新的System.Windows.Forms.DataGridViewColumn[]
{
这个月
});
this.dataGridView1.Dock=System.Windows.Forms.DockStyle.Fill;
this.dataGridView1.Location=新系统.Drawing.Point(0,0);
this.dataGridView1.Name=“dataGridView1”;
this.dataGridView1.RowHeadersWidth=100;
this.dataGridView1.Size=新系统.Drawing.Size(745532);
this.dataGridView1.TabIndex=0;
this.dataGridView1.RowValidated+=
新System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView\u行已验证);
// 
//月
// 
this.Month.HeaderText=“Month”;
this.Month.Name=“Month”;
// 
//表格1
// 
此.AutoScaleDimensions=新系统.Drawing.SizeF(6F,13F);
this.AutoScaleMode=System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize=新系统.Drawing.Size(745532);
this.Controls.Add(this.dataGridView1);
this.Name=“Form1”;
this.Text=“Form1”;
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
此选项为.resume布局(false);
}
#端区
}
}
它能工作。

是的,你能

DataGridView1.Rows[0].HeaderCell.Value = "my text";
private void dtgworkingdays\u数据绑定完成(对象发送方,DataGridViewBindingCompleteEventTarget)
{
this.FillRecordNo();
}
私有void FillRecordNo()
{
for(int i=0;i

另请参见。

确保选中了
启用列记录。

这是因为第一列(行标题列)的宽度! 增加它的宽度,然后你可以看到它的价值! 您可以使用以下命令:

dgv1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;

(注意:您必须首先设置
dgv1.RowHeadersVisible=true;

我也有同样的问题,但我注意到在
datagrid.visible
属性更改后,我的datagrid丢失了行的标题

尝试使用
Datagrid.visiblechanged
事件更新行标题。

我认为应该是:

dataGridView1.Columns[0].HeaderCell.Value = "my text";
这是一个小小的“政变”

我也有同样的问题。无法使用数据绑定网格获取标题列以显示行标题数据(简单的行号)。一旦我将代码移动到事件“DataBindingComplete”中,它就工作了

对不起,额外的代码。我想提供一个工作的例子,但没有时间把它全部删减,所以只需剪切和粘贴我的一些应用程序,并将其修复以供您运行。给你:

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();
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用系统数据;
使用System.Windows.Forms;
使用Sy
dataGridView1.Columns[0].HeaderCell.Value = "my text";
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
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();
        }
    }
}
foreach (DataGridViewRow row in datagrid.Rows)
                        row.HeaderCell.Value = String.Format("{0}", row.Index + 1);