如何在Datagridview C#中为特定列设置列标题文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1036948/
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-06 06:40:19  来源:igfitidea点击:

How to set column header text for specific column in Datagridview C#

c#.netwinformsdatagridview

提问by

How to set column header text for specific column in Datagridview C#

如何在Datagridview C#中为特定列设置列标题文本

采纳答案by TheVillageIdiot

there is HeaderTextproperty in Column object, you can find the column and set its HeaderText after initializing grid or do it in windows form designer via designer for DataGrid.

Column 对象中有HeaderText属性,您可以在初始化网格后找到该列并设置其 HeaderText 或通过 DataGrid 的设计器在 windows 窗体设计器中进行设置。

    public Form1()
    {
        InitializeComponent();

        grid.Columns[0].HeaderText = "First Column"; 
        //..............
    }

More details are hereat MSDN. More details about DataGrid are here.

更多详情,这里在MSDN。有关 DataGrid 的更多详细信息,请参见此处

回答by Colin

grid.Columns[0].HeaderText

or

或者

grid.Columns["columnname"].HeaderText

回答by Marc Gravell

For info, if you are binding to a class, you can do this in your type via DisplayNameAttribute:

有关信息,如果您绑定到一个类,您可以通过以下方式在您的类型中执行此操作DisplayNameAttribute

[DisplayName("Access key")]
public string AccessKey { get {...} set {...} }

Now the header-text on auto-generated columns will be "Access key".

现在自动生成列的标题文本将是“访问键”。

回答by reejasureshkumar

Dg_View.Columns.Add("userid","User Id");
Dg_View.Columns[0].Width = 100;

Dg_View.Columns.Add("username", "User name");
Dg_View.Columns[0].Width = 100;

回答by SomeOne

private void datagrid_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
    string test = this.datagrid.Columns[e.ColumnIndex].HeaderText;
}

This code will get the HeaderTextvalue.

此代码将获取HeaderText值。

回答by Mattia72

If you work with visual studio designer, you will probably have defined fields for each columns in the YourForm.Designer.csfile e.g.:

如果您使用 Visual Studio 设计器,您可能会为YourForm.Designer.cs文件中的每一列定义字段,例如:

private System.Windows.Forms.DataGridViewCheckBoxColumn dataGridViewCheckBoxColumn1;    
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn2; 

If you give them useful names, you can set the HeaderTexteasily:

如果您给它们提供有用的名称,则可以HeaderText轻松设置:

usefulNameForDataGridViewTextBoxColumn.HeaderText = "Useful Header Text";

回答by Mazen Ahmed

dgv.Columns[0].HeaderText = "Your Header";

dgv.Columns[0].HeaderText = "你的标题";