关闭

Dynamically Creating Bound and Template Columns in GridView

460人阅读 评论(0) 收藏 举报

Introduction:

There are situations when you need the columns to be created dynamically. Creating dynamic columns in GridView control is almost identical to Datagrid control. If you are working with Datagrid control than check out my article Creating Dynamic Bound and Template Columns in Datagrid Control. In this article we will see how to create dynamic bound and template columns for the GridView.

Dynamically Creating BoundColumn for GridView:

BoundColumns are pretty straight forward. Check out the code below:

BoundField nameColumn = new BoundField();

nameColumn.DataField = "Name";

nameColumn.HeaderText = "Person Name";

GridView1.Columns.Add(nameColumn);

All you do is make an object of the BoundField class. Assign the DataField, HeaderText and finally add it to the GridView columns collection. There must be any source from which we get the data field and in this case the source is SqlDataSource object. For more information about how to assign SqlDataSource to the GridView control please check out my GridView articles.

Dynamically Creating a Template Column:

Now let's see how we can create template columns dynamically. Since template columns can contains any control you must define a custom template which creates the controls that are identified. You can download the template file which is present in the zip file at the end of this article.

The code below shows how you can use the custom template "GridViewTemplate.cs".

TemplateField ckhColumn = new TemplateField();

ckhColumn.HeaderTemplate = new GridViewTemplate(ListItemType.Header, "CheckBox Column");

ckhColumn.ItemTemplate = new GridViewTemplate(ListItemType.Item, "some data");

GridView1.Columns.Add(ckhColumn);

First we make an instance of the TemplateField class. Than we set the HeaderTemplate type by passing the ListItemType.Header and the name of the template column to be created. Than we set the ItemTemplate and finally we add the newly created template column in the GridView columns collection.

Since I am using SqlDataSource object it will take care of binding for me but if you are using a different data source than you must call GridView1.DataBind() method to bind it on the screen.

Please view GridViewTemplate.cs file which contains the main code to create the template columns.   

I hope you liked the article, happy coding!

 

By AzamSharp
Download Source Code

 

http://gridviewguy.com/ArticleDetails.aspx?articleID=88

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:119454次
    • 积分:1911
    • 等级:
    • 排名:千里之外
    • 原创:54篇
    • 转载:71篇
    • 译文:0篇
    • 评论:9条
    文章分类
    最新评论