您可以像任何其他控件一样创建它.
在您的页面中放置一个PLACEHOLDER控件(这将作为起点)
所以你的页面看起来像
<body>
<form id="form" runat="server" />
<asp:PlaceHolder id="ph" runat="server" />
</body>
Run Code Online (Sandbox Code Playgroud)
然后,在您的代码后面,只需创建并添加控件到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);
Run Code Online (Sandbox Code Playgroud)
也许你想添加更多控件?
// 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!
Run Code Online (Sandbox Code Playgroud)
希望它有助于您入门
根据您的回复,你正在使用的WinForms。首先是一个非常简单的示例,然后根据“典型”使用场景对要考虑的问题进行一些讨论。
这是一个特定示例,其中响应在运行时单击按钮,将创建一个新的 DataGridView,将其放置在 Form 上,调整大小等:
// declare a form scoped variable to hold a reference
// to the run-time created DataGridview
private DataGridView RunTimeCreatedDataGridView;
// sample of creating the DataGridView at run-time
// and adding to the Controls collection of a Form
// and positioning and sizing
// fyi: the Form used here is sized 800 by 600
private void button1_Click(object sender, EventArgs e)
{
RunTimeCreatedDataGridView= new DataGridView();
RunTimeCreatedDataGridView.Size = new Size(300, 542);
RunTimeCreatedDataGridView.Location = new Point(10,12);
this.Controls.Add(RunTimeCreatedDataGridView);
}
Run Code Online (Sandbox Code Playgroud)
当然,您可以使用 Bounds 属性或方法 'SetBounds 简化设置大小和位置,如下所示:
RunTimeCreatedDataGridView.SetBounds(10,12,300,542);
Run Code Online (Sandbox Code Playgroud)
您可能希望通过设置 Dock 或 Anchor 属性来设置“自动”确定大小和位置的其他属性。
并且您可能希望通过向上述代码添加设置 BackGroundColor、BorderStyle 等的调用,以其他方式“自定义配置”DataGridView 的视觉外观。
到这个时候,我希望你在思考这样的事情:“那些真正重要的事情,比如配置列、数据绑定等呢?” 在 DesignTime 上通过 DataGridView 右上角和属性浏览器窗口中的“智能标记”公开的所有精彩功能怎么样?
在这里,我们得到的是一般的,而不是具体的。
如果您“确定”在某个时候运行时用户会想要创建一个 DataGridView:为什么不提前创建它:视觉样式它,创建列等,然后在表单加载时隐藏它:然后按需显示。
如果您绝对必须在运行时从头开始创建 DataGridView,但又想避免大量输入:首先在设计时创建 DataGridView,进入 Designer.cs 文件并复制自动生成的代码,该代码对您的视觉样式,添加和配置列:然后将该代码粘贴到您创建 DataGridView 的方法或事件中(是的,您需要稍微调整一下)。
由于在这种情况下,我们对您可能会或可能不会将 DataGridView 绑定到什么一无所知,因此我们将对此保持“沉默”。
在(奇怪的?偶然的机会?)您在运行时创建多个 DataGridViews 的不太可能的情况下,建议您在一个变量中维护它们的内部列表,例如List<DataGridView>并有一个命名的变量currentDataGridView,您可以依靠它来保存对当前处于活动状态(具有焦点、可见等) DataGridView。
在每种情况下,我都建议在设计时模式下对 DataGridView 使用“乱七八糟”,然后检查 Designer.cs 文件中生成的代码(但永远不要更改它!)以获取有关如何使用各种功能的快速信息数据网格视图。对于将 DataGridView 绑定到复杂数据源和格式的主要示例:请查看 CodeProject 以获取相关文章、提示等。
从 Designer.cs 文件中自动生成的代码中“收获”你需要的东西,然后,当你准备好时,删除一个 Form 上的 DataGridView 实例,并在运行时“做你自己的事”。
| 归档时间: |
|
| 查看次数: |
26827 次 |
| 最近记录: |