Introduction
Some Times you need to add columns to your GridView in runtime, here in this article I will show you how to do that in very simple steps
Background's
This Code Will show only how create columns in GridView in runtime I will not show how to get the data source you should already know how to do that
Using the code
If you have a Query as an example and you want to show the results in gridview
For example
SELECT UName,UAddress,Uphone From MyTable
In GridView if AutoGenerateColumns Set to True you will get the column name same as column name in the query
Then First you have to set
AutoGenerateColumns to false
GridView1.AutoGenerateColumns = False
And then create bound Field
Dim Field As New BoundField
Then Inside it Which data field and Header Text
Field.DataField = "UName"
Field.HeaderText = "User Name"
Then Create Data Control Field and Assign it to the bound Fild
Dim Col As DataControlField = Field
Then Add it to the GridView
GridView1.Columns.Add(Col)
The New Column is Added Now you want to add new column you have to make new resource as follows
Field = New BoundField
And then Repeat the previous Steps
Putting All Together
GridView1.AutoGenerateColumns = False
Dim Field As New BoundField
Field.DataField = "UName"
Field.HeaderText = "User Name"
Dim Col As DataControlField = Field
GridView1.Columns.Add(Col)
Field = New BoundField
Field.DataField = "UAddress"
Field.HeaderText = "User Address"
Col = Field
GridView1.Columns.Add(Col)
Field = New BoundField
Field.DataField = "UPhone"
Field.HeaderText = "User Phone Number"
Col = Field
GridView1.Columns.Add(Col)
GridView1.DataBind()
I hope This article helps