DataGrid.SetDataBinding 方法 在运行时设置 DataSource 和 DataMember 属性。
参数 dataSource System.Windows.Forms.DataGrid 控件的数据源。 dataMember DataMember 字符串,它指定该表要绑定到 DataSource 属性所返回的对象中。 异常 异常类型条件 ArgumentException 一个或多个参数无效。 ArgumentNullException dataSource 参数为 空引用(在 Visual Basic 中为 Nothing)。 备注 在运行时必须使用 SetDataBinding 方法来重置 DataSource 属性。有关设置有效数据源的更详细信息,请参见 DataSource 属性。通过将 DataView 用作数据源并将 AllowNew 属性设置为 false,可以创建网格,该网格允许用户编辑数据但禁止他们添加新行。当 DataSource 为 DataView 或 DataTable 时,请将 DataMember 设置成空字符串 ("")。
示例 示例 下面的代码示例将 DataSource 和 DataMember 分别设置为 DataSet 中的 DataSet 和 DataTable。
private void BindControls()
{ // Creates a DataSet named SuppliersProducts. DataSet SuppliersProducts = new DataSet("SuppliersProducts"); // Adds two DataTable objects, Suppliers and Products. SuppliersProducts.Tables.Add(new DataTable("Suppliers")); SuppliersProducts.Tables.Add(new DataTable("Products")); // Insert code to add DataColumn objects. // Insert code to fill tables with columns and data. // Binds the DataGrid to the DataSet, displaying the Suppliers table. dataGrid1.SetDataBinding(SuppliersProducts, "Suppliers"); }