如何动态地创建在C#中的DataGridView? [英] How do I dynamically create a DataGridView in C#?

查看:223
本文介绍了如何动态地创建在C#中的DataGridView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何动态地创建在C#中的DataGridView?能否请您提供一个例子?

How do I dynamically create a DataGridView in C#? Could you please provide an example?

推荐答案

您可以像任何其他控件创建它。

You can create it like any other controls.

放置在你的页面的占位符控制(这将作为起点)

place a PLACEHOLDER control in your page (this will serve as start point)

所以你的页面看起来像

<body>
    <form id="form" runat="server" />
    <asp:PlaceHolder id="ph" runat="server" />
</body>



然后,在你后面的代码,只需创建并添加控件占位

Then, in your code behind, just create and add controls to the Place Holder

// Let's create our Object That contains the data to show in our Grid first
string[] myData = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" };

// Create the Object
GridView gv = new GridView();

// Assign some properties
gv.ID = "myGridID";
gv.AutoGenerateColumns = true;

// Assing Data (this can be a DataTable or you can create each column through Columns Colecction)
gv.DataSource = myData;
gv.DataBind();

// Now that we have our Grid all set up, let's add it to our Place Holder Control
ph.Controls.Add(gv);



也许你想添加更多的控制?

Maybe you want to add more controls?

// How about adding a Label as well?
Label lbl = new Label;
lbl.ID = "MyLabelID";
lbl.Text = String.Format("Grid contains {0} row(s).", myData.Length);

ph.Controls.Add(lbl);

// Done!



希望它可以帮助你开始

Hope it helps get you started

这篇关于如何动态地创建在C#中的DataGridView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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