如何在C#中动态创建DataGridView?

如何在C#中动态创建DataGridView? 你能举个例子吗?

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

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

所以你的页面看起来像

 

然后,在您的代码后面,只需创建并添加控件到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); 

也许你想添加更多控件?

 // 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! 

希望它能帮助您入门

根据您的回复,您使用的是WinForms。 首先是一个非常简单的示例,然后根据“典型”使用场景对要考虑的问题进行一些讨论。

这是一个特定的示例,其中,响应于在运行时单击按钮,创建新的DataGridView,定位在窗体上,大小等等:

 // 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); } 

您当然可以使用Bounds属性或方法’SetBounds简化设置大小和位置:

  RunTimeCreatedDataGridView.SetBounds(10,12,300,542); 

您可能希望通过设置Dock或Anchor属性来设置“自动”确定大小和位置的其他属性。

并且您可能希望通过添加调用将BackGroundColor,BorderStyle等设置为上述代码来以其他方式“自定义配置”DataGridView的可视外观。

到了这个时候,我希望你能想到这样的事情:“配置列,数据绑定等真正重要的事情呢?” 通过DataGridView右上角和“属性浏览器”窗口中的“智能标记”在DesignTime中显示的所有精彩function如何呢?

这是我们获得一般性而非具体性的地方。

如果你“确定”某个时候运行时用户想要创建一个DataGridView:为什么不提前创建它:直观地设置它,创建列等,然后在Form Loads时隐藏它:然后根据需要显示它。

如果你绝对必须在运行时从头开始创建一个DataGridView,但是想要避免大量的输入:首先在设计时创建DataGridView,进入Designer.cs文件并复制出自动生成的代码,这些代码对于你有视觉风格,添加和配置列:然后将该代码粘贴到您创建DataGridView的方法或事件中(是的,您需要’稍微调整一下)。

因为,在这种情况下,我们对您可能或不可能将DataGridView绑定到什么一无所知,我们只会对那个保持“妈咪”。

在(奇怪的?关闭机会?)你在运行时创建多个DataGridViews的不太可能的情况,建议你在像List这样的变量中维护它们的内部列表,并且有一个名为currentDataGridView变量,你可以依赖它保持对当前活动的引用(具有焦点,可见等)DataGridView。

在每种情况下,我都建议在设计时模式下使用DataGridView“乱搞”,然后检查Designer.cs文件中生成的代码(但永远不要改变它!),以获得有关如何使用各种function的快速信息。 DataGridView的。 对于将DataGridView绑定到复杂DataSources和格式化的主要示例:请查看CodeProject以获取相关文章,提示等。

从Designer.cs文件中自动生成的代码“收获”您需要的内容,然后,当您准备好时,删除Form上的DataGridView实例,并在运行时“自己做”。

 GridView gv = new GridView(); gv.datasource = dt; gv.databind(); 

然后将这个gv放在面板或div或table coloumn中。

您可以查看此链接http://www.ehow.com/how_5212306_create-datagridview-c.html