注释
DataGridView 控件替换并添加 DataGrid 控件的功能;但是,如果选择,则保留 DataGrid 控件以实现后向兼容性和将来使用。 有关详细信息,请参阅 Windows 窗体 DataGridView 控件与 DataGrid 控件之间的区别。
使用设计时功能创建 Windows 窗体 DataGrid 后,你可能还希望在运行时动态更改网格 DataSet 对象的元素。 这可能包括更改表中各个数值或者更改与 DataGrid 控件绑定的数据源。 对单个值的更改是通过 DataSet 对象完成的,而不是 DataGrid 控件。
以编程方式更改数据
从 DataSet 对象中指定所需的表以及表中的所需行和字段,并将单元格设置为等于新值。
注释
若要指定 DataSet 的第一个表或表的第一行,请使用 0。
以下示例演示如何通过单击
Button1更改数据集第一行第一行的第二个条目。 之前已经创建了 DataSet (ds) 以及表(0和1)。Protected Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click ds.tables(0).rows(0)(1) = "NewEntry" End Subprivate void button1_Click(object sender, System.EventArgs e) { ds.Tables[0].Rows[0][1]="NewEntry"; }private: void button1_Click(System::Object^ sender, System::EventArgs^ e) { dataSet1->Tables[0]->Rows[0][1] = "NewEntry"; }(Visual C#、Visual C++)将以下代码置于表单的构造函数中以注册事件处理程序。
this.button1.Click += new System.EventHandler(this.button1_Click);this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);在运行时,可以使用 SetDataBinding 方法将 DataGrid 控件绑定到其他数据源。 例如,你可能有多个 ADO.NET 数据控件,每个控件都连接到不同的数据库。
通过编程更改数据源
将 SetDataBinding 方法设置为要绑定到的数据源和表的名称。
以下示例演示如何使用 SetDataBinding 方法将日期源更改为连接到 Pubs 数据库中的“作者”表的 ADO.NET 数据控件(adoPubsAuthors)。
Private Sub ResetSource() DataGrid1.SetDataBinding(adoPubsAuthors, "Authors") End Subprivate void ResetSource() { DataGrid1.SetDataBinding(adoPubsAuthors, "Authors"); }private: void ResetSource() { dataGrid1->SetDataBinding(adoPubsAuthors, "Authors"); }