Rename Windows Form DataGridView Column Header text in C# and VB.Net

Last Reply 7 months ago By pandeyism

Posted 7 months ago

I have datagridview which has datasource from datatable and I want rename header text. This datagridview some times vaires number of columns

here is example how I want rename header text

15-Aug-2018        16-Aug-2018       17-Aug-2018  etc....

Here is code i have tried but I coudn't do it

DataGridView1.DataSource = dt2
For i = 0 To DataGridView1.Columns.Count - 1
    DataGridView1.Columns(i).HeaderText = String.Empty
    DataGridView1.Columns(i).HeaderText += DateAdd(DateInterval.Day, 1, DateTimePicker1.Value)
Next
You are viewing reply posted by: pandeyism 7 months ago.
Posted 7 months ago

Hey satabeach,

Please refer below sample.

Namespaces

C#

using System.Data;

VB.Net

Imports System.Data

Code

C#

public Form1()
{
    InitializeComponent();
    DataTable dt = BindGrid();
    this.dataGridView1.DataSource = dt;
    dataGridView1.Columns["Name"].HeaderText = "CustomerName";
}

private DataTable BindGrid()
{
    using (DataTable dt = new DataTable())
    {
        dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
            new DataColumn("Name", typeof(string)),
            new DataColumn("Country",typeof(string)) });
        dt.Rows.Add(1, "John Hammond", "United States");
        dt.Rows.Add(2, "Mudassar Khan", "India");
        dt.Rows.Add(3, "Suzanne Mathews", "France");
        dt.Rows.Add(4, "Robert Schidner", "Russia");
        return dt;
    }
}

VB.Net

Public Sub New()
    InitializeComponent()
    Dim dt As DataTable = BindGrid()
    Me.dataGridView1.DataSource = dt
    Me.dataGridView1.Columns("Name").HeaderText = "CustomerName"
End Sub

Private Function BindGrid() As DataTable
    Using dt As DataTable = New DataTable()
        dt.Columns.AddRange(New DataColumn(2) {New DataColumn("Id", GetType(Integer)), New DataColumn("Name", GetType(String)), New DataColumn("Country", GetType(String))})
        dt.Rows.Add(1, "John Hammond", "United States")
        dt.Rows.Add(2, "Mudassar Khan", "India")
        dt.Rows.Add(3, "Suzanne Mathews", "France")
        dt.Rows.Add(4, "Robert Schidner", "Russia")
        Return dt
    End Using
End Function

Screenshot