Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Dynamic Gridview Columns

3.21/5 (9 votes)
7 Apr 2008CPOL 1  
Very simple article to show how to add columns to a GridView at runtime.

Introduction

Sometimes you need to add columns to your GridView dynamically. In this article, I will show you how to do that in very simple steps.

Background

This code will show only how to create columns in the GridView at runtime, I will not show how to get the data source; you should already know how to do that.

Using the code

Let's say you have a query and you want to show the results in a GridView. For example:

SQL
SELECT UName,UAddress,Uphone From MyTable

In the GridView, if AutoGenerateColumns set to True, you will get the column names the same as the column names in the query.

First you have to set AutoGenerateColumns to False.

VB
GridView1.AutoGenerateColumns = False 

And then create the bound field:

VB
Dim Field As New BoundField

Then, inside it, select the data field and the header text:

VB
Field.DataField = "UName"
Field.HeaderText = "User Name"

Now, create a DataControlField and assign it to the bound field.

VB
Dim Col As DataControlField = Field

Then, add it to the GridView:

VB
GridView1.Columns.Add(Col)

The new column is added. Now, you want to add the new column and you have to make the new resource as follows:

VB
Field = New BoundField

Repeat the previous steps. Putting it all together:

VB
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)