65.9K
CodeProject is changing. Read more.
Home

Dynamic Gridview Columns

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.21/5 (9 votes)

Apr 8, 2008

CPOL
viewsIcon

75457

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:

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.

GridView1.AutoGenerateColumns = False 

And then create the bound field:

Dim Field As New BoundField

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

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

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

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 the new column and you have to make the new resource as follows:

Field = New BoundField

Repeat the previous steps. Putting it 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.