使用运行时生成的列创建 GridView [英] Creating a GridView with columns generated at runtime

查看:22
本文介绍了使用运行时生成的列创建 GridView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 DataTable,其中的列是在运行时以编程方式生成的.然后我将此 DataTable 绑定到 GridView.我想知道的是如何创建 GridView 以适应这一点,如果不可能,我如何将 DataTable 输出为格式良好的 HTML.

I have a DataTable where the columns are generated programmatically at runtime. I then bind this DataTable to a GridView. What I'm wondering is how I can create the GridView to accommodate this, and if it's not possible, how I can output the DataTable into nicely formatted HTML.

推荐答案

GridView 有一个 AutogenerateColums-property 用于此目的.您还可以动态生成列,例如:

The GridView has an AutogenerateColums-property for this purpose. You could also generate the Columns on the fly, for example:

VB.NET

Dim tbl As New DataTable
tbl.Columns.Add("ID", GetType(Int32))
tbl.Columns.Add("Name", GetType(String))
tbl.Columns.Add("Birthday", GetType(Date))
Dim pers As DataRow = tbl.NewRow
pers("ID") = 1
pers("Name") = "Tim"
pers("Birthday") = New Date(1973, 6, 9)

使用 AutoGenerateColumns 让网格自己生成列:

use AutoGenerateColumns to let grid generate the column itself:

Me.GridView1.AutoGenerateColumns = True
Me.GridView1.DataSource = tbl
Me.GridView1.DataBind()

或动态生成列

For Each col As DataColumn In tbl.Columns
    Dim field As New BoundField
    field.DataField = col.ColumnName
    field.HeaderText = col.ColumnName
    GridView1.Columns.Add(field)
Next

C#

foreach (DataColumn col in dt.Columns)
{    
    BoundField field = new BoundField();
    field.DataField = col.ColumnName;
    field.HeaderText = col.ColumnName;
    GridView1.Columns.Add(field);
}

这篇关于使用运行时生成的列创建 GridView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆