C# 将文本添加到 DataGridView 行标题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/710064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 14:19:24  来源:igfitidea点击:

Adding Text to DataGridView Row Header

c#.netwinformsdatagridview

提问by Bailz

Does C# allow you to add a String to a RowHeader in a DataGridView? If so, how is it accomplished?

C# 是否允许您向 DataGridView 中的 RowHeader 添加字符串?如果是这样,它是如何实现的?

I'm writing a Windows Form to displayed Customer Payment Data for the year so far.

到目前为止,我正在编写一个 Windows 窗体来显示今年的客户付款数据。

The ColumnHeaders display January, February, March, etc... and rather than have a blank column with DateTime.Now.Year I would like to put it in the RowHeader to make it stand out from the actual payment data.

ColumnHeaders 显示 1 月、2 月、3 月等......而不是一个带有 DateTime.Now.Year 的空白列,我想将它放在 RowHeader 中,使其从实际支付数据中脱颖而出。

回答by BFree

Yes. First, hook into the column added event:

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

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

Then, in your event handler, just append the text you want to:

然后,在您的事件处理程序中,只需附加您想要的文本:

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

回答by Chris Doggett

You don't have to use the RowValidated event, that's just the one I used for a little test app to make sure this worked, but this will set the row (not column) header text to whatever year you specify.

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

It would probably go better in the CellFormatting event, actually.

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

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

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

EDIT: Here's the entire TestForm I used, as simple as possible to demonstrate the solution. Make sure your RowHeadersWidthis wide enough to display the text.

编辑:这是我使用的整个 TestForm,尽可能简单地演示解决方案。确保您的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
    }
}

回答by Monali

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

It works.

有用。

回答by ma7moud

yes you can

是的你可以

DataGridView1.Rows[0].HeaderCell.Value = "my text";

回答by Moon

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();
    }
}

Also see Show row number in row header of a DataGridView.

另请参阅在 DataGridView 的行标题中显示行号

回答by Silver

make sure the Enable Column Recordingis checked.

确保Enable Column Recording已检查。

回答by Majid

it's because of your first column (Rows Header column) width ! increase it's width then you can see it's value ! you can use this command:

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

dgv1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;

(notice: you must first set dgv1.RowHeadersVisible = true;)

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

回答by robson

I had the same problem, but I noticed that my datagrid lost the rows's header after the datagrid.visibleproperty changed.

我遇到了同样的问题,但我注意到我的数据网格在datagrid.visible属性更改后丢失了行的标题。

Try to update the rows's headers with the Datagrid.visiblechangedevent.

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

回答by Navya

I think it should be:

我觉得应该是:

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

回答by Marc

Here's a little "coup 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