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

查看:54
本文介绍了如何在 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.

在您的页面中放置一个 PLACEHOLDER 控件(这将作为起点)

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!

希望它可以帮助您入门

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

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