Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Add Columns to GridView Programmatically

0.00/5 (No votes)
7 Apr 2008 2  
Very Simple article to show how to add columns to gridview in runtime

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

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here