Change the Header Programmatically

ryoka012

Active member
Joined
Oct 13, 2011
Messages
32
Programming Experience
Beginner
Hi,


I have been using Datasource to populate my Datagridview.
Can any one give me an idea how can i change the header of my Datadagridview base on my code below.

Thanks in advance
VB.NET:
 With DataGridView
            .ColumnCount = 10
            .Columns(0).Name = "Custom Office Code"
            .Columns(1).Name = "Registry Number"
            .Columns(2).Name = "BL Number"
            .Columns(3).Name = "Container ID"
            .Columns(4).Name = "Container Type"
            .Columns(5).Name = "Empty Full Indicator"
            .Columns(6).Name = "Marks Seal No 1"
            .Columns(7).Name = "Marks Seal No 2"
            .Columns(8).Name = "Marks Seal No 3"
            .Columns(9).Name = "Sealing Party Code"
        End With
        Dim con As New SqlConnection(SQLConn)
        Try
            con.Open()
            Dim cmd As SqlCommand = con.CreateCommand
            cmd.CommandText = "Select * from CTN"
            cmd.CommandType = CommandType.Text
            Dim dr As SqlDataReader = cmd.ExecuteReader
            Dim dt As New DataTable
            dt.Load(dr)
            DataGridView.DataSource = dt


        Catch ex As Exception
      
        Finally
            If con IsNot Nothing Then
                con.Close()
                con.Dispose()
            End If
        End Try
 
Thanks john for the reply.

Yes but i have tried that also but same problem.
It generates the Header of the Table Column Name.
 
Hi,

From what I am guessing you are wanting to be able to control the Columns being added to the DataGridView when the Datasource is applied? If so, have a look at this:-

With SomeDataGridView
  .AutoGenerateColumns = False
  .Columns.Add(New DataGridViewTextBoxColumn With {.Name = "SomeName", .HeaderText = "SomeHeadertext"})
  With .Columns(0)
    .DataPropertyName = "SomePropertyNameInTheDatasource"
    .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
    .HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
  End With
  .DataSource = SomeDataSource
End With


The important thing here is that the AutoGenerateColumns Property has been set to False. This than allows you to create only that Columns that you want to see and then Bind the Data to be seen from the Datasource via the DataPropertyName of each individual column.

I have just shown the above as an example so that you can see how things work but in essence what can be created at design time, rather than runtime, should be done in the designer at design time.

Hope that helps.

Cheers,

Ian
 
Back
Top