DataSet与GridView绑定

前台代码:

<table border="0" cellpadding="0" cellspacing="0">

            <tr>

                <td>

                    <strong>Dynamic Grid</strong></td>

            </tr>

            <tr>

                <td>

                    <asp:GridView ID="GrdDynamic" runat="server"AutoGenerateColumns="False">

                    <Columns>

                    </Columns>

                    </asp:GridView>

                   

                </td>

            </tr>

        </table>

 

后台代码:

public partial class _Default : System.Web.UI.Page

{

    #region constants

    const string NAME = "NAME";

    const string ID = "ID";

    #endregion

 

    protected void Page_Load(object sender, EventArgs e)

    {

        loadDynamicGrid();

    }

 

    private void loadDynamicGrid()

    {

        #region Code for preparing the DataTable

 

        //Create an instance of DataTable

        DataTable dt = new DataTable();

       

        //Create an ID column for adding to the Datatable

        DataColumn dcol = new DataColumn(ID ,typeof(System.Int32));

        dcol.AutoIncrement = true;

        dt.Columns.Add(dcol);

 

        //Create an ID column for adding to the Datatable

        dcol = new DataColumn(NAME, typeof(System.String));

        dt.Columns.Add(dcol);

 

        //Now add data for dynamic columns

        //As the first column is auto-increment, we do not have to add any thing.

        //Let's add some data to the second column.

        for (int nIndex = 0; nIndex < 10; nIndex++)

        {

            //Create a new row

            DataRow drow = dt.NewRow();

 

            //Initialize the row data.

            drow[NAME] = "Row-" + Convert.ToString((nIndex + 1));

 

            //Add the row to the datatable.

            dt.Rows.Add(drow);

        }

        #endregion

 

        //Iterate through the columns of the datatable to set the data bound field dynamically.

        foreach (DataColumn col in dt.Columns)

        {

            //Declare the bound field and allocate memory for the bound field.

            BoundField bfield = new BoundField();

 

            //Initalize the DataField value.

            bfield.DataField = col.ColumnName;

 

            //Initialize the HeaderText field value.

            bfield.HeaderText = col.ColumnName;

 

            //Add the newly created bound field to the GridView.

            GrdDynamic.Columns.Add(bfield);

        }

 

        //Initialize the DataSource

        GrdDynamic.DataSource = dt;

 

        //Bind the datatable with the GridView.

        GrdDynamic.DataBind();

    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值