如何:在运行时更改 Windows 窗体 DataGrid 控件中显示的数据

更新:2007 年 11 月

说明:

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 Sub
    
    private 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 方法将数据源更改为一个 ADO.NET 数据控件 (adoPubsAuthors),此数据控件连接到 Pubs 数据库中的 Authors 表。

    Private Sub ResetSource()
       DataGrid1.SetDataBinding(adoPubsAuthors, "Authors")
    End Sub
    
    private void ResetSource()
    {
       DataGrid1.SetDataBinding(adoPubsAuthors, "Authors");
    }
    
    private:
       void ResetSource()
       {
          dataGrid1->SetDataBinding(adoPubsAuthors, "Authors");
       }
    

请参见

任务

如何:在 Windows 窗体 DataGrid 控件中删除或隐藏列

如何:向 Windows 窗体 DataGrid 控件添加表和列

如何:将 Windows 窗体 DataGrid 控件绑定到数据源

概念

数据集 (ADO.NET)