Csharp/CSharp Tutorial/ADO.Net/DataGrid

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Binding DataSet to DataGrid

using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
  public class Form1 : System.Windows.Forms.Form
  {
        private System.Windows.Forms.DataGrid dataGrid1;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Button button1;
    public Form1()
    {
            this.dataGrid1 = new System.Windows.Forms.DataGrid();
            this.label1 = new System.Windows.Forms.Label();
            this.button1 = new System.Windows.Forms.Button();
            ((System.ruponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
            this.SuspendLayout();
            // 
            this.dataGrid1.DataMember = "";
            this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
            this.dataGrid1.Location = new System.Drawing.Point(16, 56);
            this.dataGrid1.Name = "dataGrid1";
            this.dataGrid1.Size = new System.Drawing.Size(264, 168);
            this.dataGrid1.TabIndex = 0;
            // 
            this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 24F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
            this.label1.Location = new System.Drawing.Point(8, 8);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(296, 40);
            this.label1.TabIndex = 1;
            this.label1.Text = "Databases in Code";
            // 
            this.button1.Location = new System.Drawing.Point(80, 240);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(120, 23);
            this.button1.TabIndex = 2;
            this.button1.Text = "Connect to database";
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(292, 273);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.dataGrid1);
            this.Name = "Form1";
            this.Text = "Form1";
            ((System.ruponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
            this.ResumeLayout(false);
        }
    [STAThread]
    static void Main() 
    {
      Application.Run(new Form1());
    }
        private void button1_Click(object sender, System.EventArgs e)
        {
            DataSet dataset1 = new DataSet("dataset1");
            string connectionString = "workstation id=STEVE;packet size=4096;integrated security=SSPI;initial catalog=pubs;persist security info=False";
            SqlConnection connection1 = new SqlConnection(connectionString);
            SqlCommand command1 = new SqlCommand("SELECT * FROM authors");
            command1.rumandType = CommandType.Text;
            connection1.Open();
            command1.Connection = connection1;
            SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter();
            sqlDataAdapter1.SelectCommand = command1;
            sqlDataAdapter1.Fill(dataset1, "authors");
            dataGrid1.SetDataBinding(dataset1, "authors");
        }
  }

Data binding for Multiple Controls

using System.Data.SqlClient;
using System.Data;
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
  public class MultipleControls : System.Windows.Forms.Form
  {
    private System.Windows.Forms.DataGrid dataGrid1;
    private System.Windows.Forms.ruboBox cboCustomerID;
    private System.Windows.Forms.Button button1;
    private System.Windows.Forms.Label label1;
    private System.Windows.Forms.TextBox txtCustomerID;
    private System.Windows.Forms.Label label2;
    private System.Windows.Forms.Label label3;
    private System.Windows.Forms.TextBox txtContactName;
    public MultipleControls()
    {
      this.dataGrid1 = new System.Windows.Forms.DataGrid();
      this.cboCustomerID = new System.Windows.Forms.ruboBox();
      this.button1 = new System.Windows.Forms.Button();
      this.label1 = new System.Windows.Forms.Label();
      this.txtCustomerID = new System.Windows.Forms.TextBox();
      this.label2 = new System.Windows.Forms.Label();
      this.label3 = new System.Windows.Forms.Label();
      this.txtContactName = new System.Windows.Forms.TextBox();
      ((System.ruponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
      this.SuspendLayout();
      // 
      this.dataGrid1.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
        | System.Windows.Forms.AnchorStyles.Left) 
        | System.Windows.Forms.AnchorStyles.Right);
      this.dataGrid1.CaptionVisible = false;
      this.dataGrid1.DataMember = "";
      this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
      this.dataGrid1.Location = new System.Drawing.Point(12, 112);
      this.dataGrid1.Name = "dataGrid1";
      this.dataGrid1.Size = new System.Drawing.Size(436, 168);
      this.dataGrid1.TabIndex = 1;
      // 
      // cboCustomerID
      // 
      this.cboCustomerID.DropDownStyle = System.Windows.Forms.ruboBoxStyle.DropDownList;
      this.cboCustomerID.Location = new System.Drawing.Point(120, 8);
      this.cboCustomerID.Name = "cboCustomerID";
      this.cboCustomerID.Size = new System.Drawing.Size(260, 21);
      this.cboCustomerID.TabIndex = 2;
      // 
      // button1
      // 
      this.button1.Location = new System.Drawing.Point(340, 80);
      this.button1.Name = "button1";
      this.button1.Size = new System.Drawing.Size(104, 24);
      this.button1.TabIndex = 3;
      this.button1.Text = "Test";
      this.button1.Visible = false;
      this.button1.Click += new System.EventHandler(this.button1_Click);
      // 
      // label1
      // 
      this.label1.Location = new System.Drawing.Point(12, 12);
      this.label1.Name = "label1";
      this.label1.Size = new System.Drawing.Size(96, 20);
      this.label1.TabIndex = 4;
      this.label1.Text = "Select By ID:";
      // 
      // txtCustomerID
      // 
      this.txtCustomerID.Location = new System.Drawing.Point(120, 44);
      this.txtCustomerID.Name = "txtCustomerID";
      this.txtCustomerID.Size = new System.Drawing.Size(188, 21);
      this.txtCustomerID.TabIndex = 5;
      this.txtCustomerID.Text = "";
      // 
      // label2
      // 
      this.label2.Location = new System.Drawing.Point(12, 48);
      this.label2.Name = "label2";
      this.label2.Size = new System.Drawing.Size(80, 16);
      this.label2.TabIndex = 6;
      this.label2.Text = "Customter ID:";
      // 
      // label3
      // 
      this.label3.Location = new System.Drawing.Point(12, 72);
      this.label3.Name = "label3";
      this.label3.Size = new System.Drawing.Size(104, 16);
      this.label3.TabIndex = 7;
      this.label3.Text = "Contact Name:";
      // 
      // txtContactName
      // 
      this.txtContactName.Location = new System.Drawing.Point(120, 68);
      this.txtContactName.Name = "txtContactName";
      this.txtContactName.Size = new System.Drawing.Size(188, 21);
      this.txtContactName.TabIndex = 8;
      this.txtContactName.Text = "";
      // 
      // MultipleControls
      // 
      this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
      this.ClientSize = new System.Drawing.Size(456, 294);
      this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                      this.txtContactName,
                                      this.label3,
                                      this.label2,
                                      this.txtCustomerID,
                                      this.label1,
                                      this.button1,
                                      this.cboCustomerID,
                                      this.dataGrid1});
      this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
      this.Load += new System.EventHandler(this.MultipleControls_Load);
      ((System.ruponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
      this.ResumeLayout(false);
    }
    private void MultipleControls_Load(object sender, System.EventArgs e)
    {
      string connectionString = @"Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI";
      string SQL = "SELECT * FROM Customers";
      SqlConnection con = new SqlConnection(connectionString);
      SqlCommand com = new SqlCommand(SQL, con);
      SqlDataAdapter adapter = new SqlDataAdapter(com);
      DataSet ds = new DataSet("Northwind");      
      con.Open();
      adapter.Fill(ds, "Customers");
      com.rumandText = "SELECT * FROM Products";
      adapter.Fill(ds, "Products");
      com.rumandText = "SELECT * FROM Suppliers";
      adapter.Fill(ds, "Suppliers");
      con.Close();
      dataGrid1.DataSource = ds.Tables["Customers"].DefaultView;
      cboCustomerID.DataSource = ds.Tables["Customers"].DefaultView;
      cboCustomerID.DisplayMember = "CustomerID";
      txtCustomerID.DataBindings.Add("Text", ds.Tables["Customers"].DefaultView,"CustomerID");
      txtContactName.DataBindings.Add("Text", ds.Tables["Customers"].DefaultView,"ContactName");
    }
    private void button1_Click(object sender, System.EventArgs e)
    {
      BindingContext binding = this.BindingContext;
      BindingManagerBase currency = binding[cboCustomerID.DataSource];
      
      DataRowView drView = (DataRowView)currency.Current;
      MessageBox.Show(drView["CustomerID"].ToString());
    }
    [STAThread]
    static void Main() 
    {
      Application.Run(new MultipleControls());
    }
  }

DataGrid View: on data error

using System;
using System.Collections.Generic;
using System.ruponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

public class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        List<SimpleDataItem> items = new List<SimpleDataItem>();
        for (int i = 0; i < 10; i++)
        {
            SimpleDataItem item = new SimpleDataItem();
            item.SomeVal = i;
            item.Var = "Hi";
            items.Add(item);
        }

        simpleDataItemBindingSource.DataSource = items;
    }
    private void OnDataError(object sender, DataGridViewDataErrorEventArgs e)
    {
        System.Console.WriteLine(e.Exception.GetType());
        System.Console.WriteLine(e.Exception.Message);
        System.Console.WriteLine(e.Context);
    }
    private void InitializeComponent()
    {
        this.simpleDataItemDataGridView = new System.Windows.Forms.DataGridView();
        this.SomeVal = new System.Windows.Forms.DataGridViewTextBoxColumn();
        this.Var = new System.Windows.Forms.DataGridViewTextBoxColumn();
        this.dataGridView1 = new System.Windows.Forms.DataGridView();
        this.simpleDataItemBindingNavigator = new System.Windows.Forms.BindingNavigator();
        this.bindingNavigatorAddNewItem = new System.Windows.Forms.ToolStripButton();
        this.bindingNavigatorCountItem = new System.Windows.Forms.ToolStripLabel();
        this.bindingNavigatorDeleteItem = new System.Windows.Forms.ToolStripButton();
        this.bindingNavigatorMoveFirstItem = new System.Windows.Forms.ToolStripButton();
        this.bindingNavigatorMovePreviousItem = new System.Windows.Forms.ToolStripButton();
        this.bindingNavigatorSeparator = new System.Windows.Forms.ToolStripSeparator();
        this.bindingNavigatorPositionItem = new System.Windows.Forms.ToolStripTextBox();
        this.bindingNavigatorSeparator1 = new System.Windows.Forms.ToolStripSeparator();
        this.bindingNavigatorMoveNextItem = new System.Windows.Forms.ToolStripButton();
        this.bindingNavigatorMoveLastItem = new System.Windows.Forms.ToolStripButton();
        this.bindingNavigatorSeparator2 = new System.Windows.Forms.ToolStripSeparator();
        this.bindingNavigatorSaveItem = new System.Windows.Forms.ToolStripButton();
        this.dataGridViewTextBoxColumn3 = new System.Windows.Forms.DataGridViewTextBoxColumn();
        this.dataGridViewTextBoxColumn4 = new System.Windows.Forms.DataGridViewTextBoxColumn();
        this.simpleDataItemBindingSource = new System.Windows.Forms.BindingSource();
        ((System.ruponentModel.ISupportInitialize)(this.simpleDataItemDataGridView)).BeginInit();
        ((System.ruponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
        ((System.ruponentModel.ISupportInitialize)(this.simpleDataItemBindingNavigator)).BeginInit();
        this.simpleDataItemBindingNavigator.SuspendLayout();
        ((System.ruponentModel.ISupportInitialize)(this.simpleDataItemBindingSource)).BeginInit();
        this.SuspendLayout();
        // 
        // simpleDataItemDataGridView
        // 
        this.simpleDataItemDataGridView.AutoGenerateColumns = false;
        this.simpleDataItemDataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.SomeVal,
            this.Var});
        this.simpleDataItemDataGridView.Location = new System.Drawing.Point(27, 32);
        this.simpleDataItemDataGridView.Name = "simpleDataItemDataGridView";
        this.simpleDataItemDataGridView.Size = new System.Drawing.Size(300, 220);
        this.simpleDataItemDataGridView.TabIndex = 1;
        // 
        // SomeVal
        // 
        this.SomeVal.DataPropertyName = "SomeVal";
        this.SomeVal.HeaderText = "SomeVal";
        this.SomeVal.Name = "SomeVal";
        // 
        // Var
        // 
        this.Var.DataPropertyName = "Var";
        this.Var.HeaderText = "Var";
        this.Var.Name = "Var";
        // 
        // dataGridView1
        // 
        this.dataGridView1.AutoGenerateColumns = false;
        this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.dataGridViewTextBoxColumn3,
            this.dataGridViewTextBoxColumn4});
        this.dataGridView1.DataSource = this.simpleDataItemBindingSource;
        this.dataGridView1.Location = new System.Drawing.Point(27, 39);
        this.dataGridView1.Name = "dataGridView1";
        this.dataGridView1.Size = new System.Drawing.Size(300, 220);
        this.dataGridView1.TabIndex = 3;
        this.dataGridView1.DataError += new System.Windows.Forms.DataGridViewDataErrorEventHandler(this.OnDataError);
        // 
        // simpleDataItemBindingNavigator
        // 
        this.simpleDataItemBindingNavigator.AddNewItem = this.bindingNavigatorAddNewItem;
        this.simpleDataItemBindingNavigator.BindingSource = this.simpleDataItemBindingSource;
        this.simpleDataItemBindingNavigator.CountItem = this.bindingNavigatorCountItem;
        this.simpleDataItemBindingNavigator.DeleteItem = this.bindingNavigatorDeleteItem;
        this.simpleDataItemBindingNavigator.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.bindingNavigatorMoveFirstItem,
            this.bindingNavigatorMovePreviousItem,
            this.bindingNavigatorSeparator,
            this.bindingNavigatorPositionItem,
            this.bindingNavigatorCountItem,
            this.bindingNavigatorSeparator1,
            this.bindingNavigatorMoveNextItem,
            this.bindingNavigatorMoveLastItem,
            this.bindingNavigatorSeparator2,
            this.bindingNavigatorAddNewItem,
            this.bindingNavigatorDeleteItem,
            this.bindingNavigatorSaveItem});
        this.simpleDataItemBindingNavigator.Location = new System.Drawing.Point(0, 0);
        this.simpleDataItemBindingNavigator.MoveFirstItem = this.bindingNavigatorMoveFirstItem;
        this.simpleDataItemBindingNavigator.MoveLastItem = this.bindingNavigatorMoveLastItem;
        this.simpleDataItemBindingNavigator.MoveNextItem = this.bindingNavigatorMoveNextItem;
        this.simpleDataItemBindingNavigator.MovePreviousItem = this.bindingNavigatorMovePreviousItem;
        this.simpleDataItemBindingNavigator.Name = "simpleDataItemBindingNavigator";
        this.simpleDataItemBindingNavigator.PositionItem = this.bindingNavigatorPositionItem;
        this.simpleDataItemBindingNavigator.Size = new System.Drawing.Size(375, 25);
        this.simpleDataItemBindingNavigator.TabIndex = 2;
        this.simpleDataItemBindingNavigator.Text = "bindingNavigator1";
        // 
        // bindingNavigatorAddNewItem
        // 
        this.bindingNavigatorAddNewItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
        this.bindingNavigatorAddNewItem.Name = "bindingNavigatorAddNewItem";
        this.bindingNavigatorAddNewItem.Size = new System.Drawing.Size(23, 22);
        this.bindingNavigatorAddNewItem.Text = "Add new";
        // 
        // bindingNavigatorCountItem
        // 
        this.bindingNavigatorCountItem.Name = "bindingNavigatorCountItem";
        this.bindingNavigatorCountItem.Size = new System.Drawing.Size(36, 22);
        this.bindingNavigatorCountItem.Text = "of {0}";
        this.bindingNavigatorCountItem.ToolTipText = "Total number of items";
        // 
        // bindingNavigatorDeleteItem
        // 
        this.bindingNavigatorDeleteItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
        this.bindingNavigatorDeleteItem.Name = "bindingNavigatorDeleteItem";
        this.bindingNavigatorDeleteItem.Size = new System.Drawing.Size(23, 22);
        this.bindingNavigatorDeleteItem.Text = "Delete";
        // 
        // bindingNavigatorMoveFirstItem
        // 
        this.bindingNavigatorMoveFirstItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
        this.bindingNavigatorMoveFirstItem.Name = "bindingNavigatorMoveFirstItem";
        this.bindingNavigatorMoveFirstItem.Size = new System.Drawing.Size(23, 22);
        this.bindingNavigatorMoveFirstItem.Text = "Move first";
        // 
        // bindingNavigatorMovePreviousItem
        // 
        this.bindingNavigatorMovePreviousItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
        this.bindingNavigatorMovePreviousItem.Name = "bindingNavigatorMovePreviousItem";
        this.bindingNavigatorMovePreviousItem.Size = new System.Drawing.Size(23, 22);
        this.bindingNavigatorMovePreviousItem.Text = "Move previous";
        // 
        // bindingNavigatorSeparator
        // 
        this.bindingNavigatorSeparator.Name = "bindingNavigatorSeparator";
        this.bindingNavigatorSeparator.Size = new System.Drawing.Size(6, 25);
        // 
        // bindingNavigatorPositionItem
        // 
        this.bindingNavigatorPositionItem.Name = "bindingNavigatorPositionItem";
        this.bindingNavigatorPositionItem.Size = new System.Drawing.Size(50, 25);
        this.bindingNavigatorPositionItem.Text = "0";
        this.bindingNavigatorPositionItem.ToolTipText = "Current position";
        // 
        // bindingNavigatorSeparator1
        // 
        this.bindingNavigatorSeparator1.Name = "bindingNavigatorSeparator1";
        this.bindingNavigatorSeparator1.Size = new System.Drawing.Size(6, 25);
        // 
        // bindingNavigatorMoveNextItem
        // 
        this.bindingNavigatorMoveNextItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
        this.bindingNavigatorMoveNextItem.Name = "bindingNavigatorMoveNextItem";
        this.bindingNavigatorMoveNextItem.Size = new System.Drawing.Size(23, 22);
        this.bindingNavigatorMoveNextItem.Text = "Move next";
        // 
        // bindingNavigatorMoveLastItem
        // 
        this.bindingNavigatorMoveLastItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
        this.bindingNavigatorMoveLastItem.Name = "bindingNavigatorMoveLastItem";
        this.bindingNavigatorMoveLastItem.Size = new System.Drawing.Size(23, 22);
        this.bindingNavigatorMoveLastItem.Text = "Move last";
        // 
        // bindingNavigatorSeparator2
        // 
        this.bindingNavigatorSeparator2.Name = "bindingNavigatorSeparator2";
        this.bindingNavigatorSeparator2.Size = new System.Drawing.Size(6, 25);
        // 
        // bindingNavigatorSaveItem
        // 
        this.bindingNavigatorSaveItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
        this.bindingNavigatorSaveItem.Enabled = false;
        this.bindingNavigatorSaveItem.Name = "bindingNavigatorSaveItem";
        this.bindingNavigatorSaveItem.Size = new System.Drawing.Size(23, 22);
        this.bindingNavigatorSaveItem.Text = "Save Data";
        // 
        // dataGridViewTextBoxColumn3
        // 
        this.dataGridViewTextBoxColumn3.DataPropertyName = "SomeVal";
        this.dataGridViewTextBoxColumn3.HeaderText = "SomeVal";
        this.dataGridViewTextBoxColumn3.Name = "dataGridViewTextBoxColumn3";
        // 
        // dataGridViewTextBoxColumn4
        // 
        this.dataGridViewTextBoxColumn4.DataPropertyName = "Var";
        this.dataGridViewTextBoxColumn4.HeaderText = "Var";
        this.dataGridViewTextBoxColumn4.Name = "dataGridViewTextBoxColumn4";
        // 
        // simpleDataItemBindingSource
        // 
        this.simpleDataItemBindingSource.DataSource = typeof(SimpleDataItem);
        // 
        // Form1
        // 
        this.ClientSize = new System.Drawing.Size(375, 266);
        this.Controls.Add(this.dataGridView1);
        this.Controls.Add(this.simpleDataItemBindingNavigator);
        this.Name = "Form1";
        ((System.ruponentModel.ISupportInitialize)(this.simpleDataItemDataGridView)).EndInit();
        ((System.ruponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
        ((System.ruponentModel.ISupportInitialize)(this.simpleDataItemBindingNavigator)).EndInit();
        this.simpleDataItemBindingNavigator.ResumeLayout(false);
        this.simpleDataItemBindingNavigator.PerformLayout();
        ((System.ruponentModel.ISupportInitialize)(this.simpleDataItemBindingSource)).EndInit();
        this.ResumeLayout(false);
        this.PerformLayout();
    }

    private System.Windows.Forms.DataGridView simpleDataItemDataGridView;
    private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn1;
    private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn2;
    private System.Windows.Forms.DataGridViewTextBoxColumn SomeVal;
    private System.Windows.Forms.DataGridViewTextBoxColumn Var;
    private System.Windows.Forms.BindingSource simpleDataItemBindingSource;
    private System.Windows.Forms.DataGridView dataGridView1;
    private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn3;
    private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn4;
    private System.Windows.Forms.BindingNavigator simpleDataItemBindingNavigator;
    private System.Windows.Forms.ToolStripButton bindingNavigatorAddNewItem;
    private System.Windows.Forms.ToolStripLabel bindingNavigatorCountItem;
    private System.Windows.Forms.ToolStripButton bindingNavigatorDeleteItem;
    private System.Windows.Forms.ToolStripButton bindingNavigatorMoveFirstItem;
    private System.Windows.Forms.ToolStripButton bindingNavigatorMovePreviousItem;
    private System.Windows.Forms.ToolStripSeparator bindingNavigatorSeparator;
    private System.Windows.Forms.ToolStripTextBox bindingNavigatorPositionItem;
    private System.Windows.Forms.ToolStripSeparator bindingNavigatorSeparator1;
    private System.Windows.Forms.ToolStripButton bindingNavigatorMoveNextItem;
    private System.Windows.Forms.ToolStripButton bindingNavigatorMoveLastItem;
    private System.Windows.Forms.ToolStripSeparator bindingNavigatorSeparator2;
    private System.Windows.Forms.ToolStripButton bindingNavigatorSaveItem;

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.Run(new Form1());
    }
}
class SimpleDataItem
{
    private int m_SomeVal;
    public int SomeVal
    {
        get { throw new ArgumentException("foo"); }
        set { m_SomeVal = value; }
    }
    private string m_SomeVar;
    public string Var
    {
        get { return m_SomeVar; }
        set { m_SomeVar = value; }
    }
}

Link two DataTable in a DataGrid

using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.rumon;
public class DataTableLinkinDataGrid : System.Windows.Forms.Form
{
  private System.Windows.Forms.DataGrid dataGrid1;
  private System.Data.DataSet dtSet;
  public DataTableLinkinDataGrid()
  {
    this.dataGrid1 = new System.Windows.Forms.DataGrid();
    ((System.ruponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
    this.SuspendLayout();
    // 
    this.dataGrid1.DataMember = "";
    this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
    this.dataGrid1.Location = new System.Drawing.Point(16, 8);
    this.dataGrid1.Size = new System.Drawing.Size(384, 240);
    // 
    // DataTableLinkinDataGrid
    // 
    this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
    this.ClientSize = new System.Drawing.Size(416, 273);
    this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                    this.dataGrid1});
    ((System.ruponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
    this.ResumeLayout(false);
    
    CreateCustomersTable();
        CreateOrdersTable();
        BindData();
  }
  [STAThread]
  static void Main() 
  {
    Application.Run(new DataTableLinkinDataGrid());
  }
  private void CreateCustomersTable()
  {
    System.Data.DataTable custTable = new DataTable("Customers");
    DataColumn dtColumn;
    DataRow myDataRow;
    dtColumn = new DataColumn();
    dtColumn.DataType = System.Type.GetType("System.Int32");
    dtColumn.ColumnName = "id";
    dtColumn.Caption = "Cust ID";
    dtColumn.ReadOnly = true;
    dtColumn.Unique = true;
    custTable.Columns.Add(dtColumn);
    dtColumn = new DataColumn();
    dtColumn.DataType = System.Type.GetType("System.String");
    dtColumn.ColumnName = "Name";
    dtColumn.Caption = "Cust Name";
    dtColumn.AutoIncrement = false;
    dtColumn.ReadOnly = false;
    dtColumn.Unique = false;
    custTable.Columns.Add(dtColumn);

    dtColumn = new DataColumn();
    dtColumn.DataType = System.Type.GetType("System.String");
    dtColumn.ColumnName = "Address";
    dtColumn.Caption = "Address";
    dtColumn.ReadOnly = false;
    dtColumn.Unique = false;
    custTable.Columns.Add(dtColumn);
    DataColumn[] PrimaryKeyColumns = new DataColumn[1];
    PrimaryKeyColumns[0] = custTable.Columns["id"];
    custTable.PrimaryKey = PrimaryKeyColumns;
    dtSet = new DataSet("Customers");
    dtSet.Tables.Add(custTable);
    myDataRow = custTable.NewRow();
    myDataRow["id"] = 1001;
    myDataRow["Address"] = "address 1";
    myDataRow["Name"] = "G";
    custTable.Rows.Add(myDataRow);
    myDataRow = custTable.NewRow();
    myDataRow["id"] = 1002;
    myDataRow["Name"] = "R";
    myDataRow["Address"] = "address 2";
    custTable.Rows.Add(myDataRow);
    myDataRow = custTable.NewRow();
    myDataRow["id"] = 1003;
    myDataRow["Name"] = "M";
    myDataRow["Address"] = "address 3";
    custTable.Rows.Add(myDataRow);
    
  }
  private void CreateOrdersTable()
  {
    DataTable ordersTable = new DataTable("Orders");
    DataColumn dtColumn;
    DataRow dtRow;
    dtColumn = new DataColumn();
    dtColumn.DataType= System.Type.GetType("System.Int32");
    dtColumn.ColumnName = "OrderId";
    dtColumn.AutoIncrement = true;
    dtColumn.Caption = "Order ID";
    dtColumn.ReadOnly = true;
    dtColumn.Unique = true;
    ordersTable.Columns.Add(dtColumn);
    dtColumn = new DataColumn();
    dtColumn.DataType= System.Type.GetType("System.String");
    dtColumn.ColumnName = "Name";
    dtColumn.Caption = "Item Name";
    ordersTable.Columns.Add(dtColumn);
    // Create CustId column which reprence CustId from 
    // the custTable
    dtColumn = new DataColumn();
    dtColumn.DataType= System.Type.GetType("System.Int32");
    dtColumn.ColumnName = "CustId";
    dtColumn.AutoIncrement = false;
    dtColumn.Caption = "CustId";
    dtColumn.ReadOnly = false;
    dtColumn.Unique = false;
    ordersTable.Columns.Add(dtColumn);
    dtColumn = new DataColumn();
    dtColumn.DataType= System.Type.GetType("System.String");
    dtColumn.ColumnName = "Description";
    dtColumn.Caption = "Description Name";
    ordersTable.Columns.Add(dtColumn);
    dtSet.Tables.Add(ordersTable);
    dtRow = ordersTable.NewRow();
    dtRow["OrderId"] = 0;
    dtRow["Name"] = "Book";
    dtRow["CustId"] = 1001 ;
    dtRow["Description"] = "desc 1" ;
    ordersTable.Rows.Add(dtRow);
    
    dtRow = ordersTable.NewRow();
    dtRow["OrderId"] = 1;
    dtRow["Name"] = "Book";
    dtRow["CustId"] = 1001 ;
    dtRow["Description"] = "desc 2" ;
    ordersTable.Rows.Add(dtRow);
  }
    private void BindData()
    {
        DataRelation dtRelation;
        DataColumn CustCol = dtSet.Tables["Customers"].Columns["id"];
        DataColumn orderCol = dtSet.Tables["Orders"].Columns["CustId"];
        
        dtRelation = new DataRelation("CustOrderRelation", CustCol, orderCol);
        dtSet.Tables["Orders"].ParentRelations.Add(dtRelation);
        dataGrid1.SetDataBinding(dtSet,"Customers");
    }       

}

Load data in DataTable to DataGrid

using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
public class DataTableCreateInCode : System.Windows.Forms.Form
{
  private System.Windows.Forms.DataGrid dataGrid1;
  private System.ruponentModel.Container components = null;
  public DataTableCreateInCode()
  {
    InitializeComponent();
  
    // dcConstructorsTest();
    CreateCustTable();    
    }
  protected override void Dispose( bool disposing )
  {
    if( disposing )
    {
      if (components != null) 
      {
        components.Dispose();
      }
    }
    base.Dispose( disposing );
  }
  private void InitializeComponent()
  {
    this.dataGrid1 = new System.Windows.Forms.DataGrid();
    ((System.ruponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
    this.SuspendLayout();
    // 
    // dataGrid1
    // 
    this.dataGrid1.DataMember = "";
    this.dataGrid1.Location = new System.Drawing.Point(8, 8);
    this.dataGrid1.Name = "dataGrid1";
    this.dataGrid1.Size = new System.Drawing.Size(400, 264);
    this.dataGrid1.TabIndex = 0;
    // 
    // DataTableCreateInCode
    // 
    this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
    this.ClientSize = new System.Drawing.Size(416, 285);
    this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                    this.dataGrid1});
    this.Name = "DataTableCreateInCode";
    this.Text = "DataTableCreateInCode";
    ((System.ruponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
    this.ResumeLayout(false);
  }
  [STAThread]
  static void Main() 
  {
    Application.Run(new DataTableCreateInCode());
  }

  private void dcConstructorsTest()
  {
    // Create Customers table
    DataTable custTable = new DataTable("Customers");
    DataSet dtSet = new DataSet();
    // Create Price Column          
    System.Type myDataType;
    myDataType = System.Type.GetType("System.Int32");
    DataColumn priceCol = new DataColumn("Price", myDataType );
    priceCol.Caption = "Price";
    custTable.Columns.Add(priceCol);
    // Create Quantity Column
    DataColumn qtCol = new DataColumn("Quantity");
    qtCol.DataType = System.Type.GetType("System.Int32");
    qtCol.Caption = "Quantity";
    custTable.Columns.Add(qtCol);
        
    // Creating an expression
    string strExpr = "Price * Quantity";
    // Create Total Column, which is result of Price*Quantity
    DataColumn totCol = new DataColumn("Total", myDataType, strExpr, MappingType.Attribute);
    totCol.Caption = "Total";
    // Add Name column to the table.
    custTable.Columns.Add(totCol);
    // Add custTable to DataSet
    dtSet.Tables.Add(custTable);
    // Bind dataset to the data grid
    dataGrid1.SetDataBinding(dtSet,"Customers");
  }

  // Create a DataTable
  private void CreateCustTable()
  {
    // Create a new DataTable
    DataTable custTable = new DataTable("Customers");
    // Create ID Column
    DataColumn IdCol = new DataColumn();
    IdCol.ColumnName= "ID";
    IdCol.DataType = Type.GetType("System.Int32");
    IdCol.ReadOnly = true;
    IdCol.AllowDBNull = false;
    IdCol.Unique = true;
    IdCol.AutoIncrement = true;
    IdCol.AutoIncrementSeed = 1;
    IdCol.AutoIncrementStep = 1;
    custTable.Columns.Add(IdCol);
    // Create Name Column
    DataColumn nameCol = new DataColumn();
    nameCol.ColumnName= "Name";
    nameCol.DataType = Type.GetType("System.String");
    custTable.Columns.Add(nameCol);
    // Create Address Column
    DataColumn addCol = new DataColumn();
    addCol.ColumnName= "Address";
    addCol.DataType = Type.GetType("System.String");
    custTable.Columns.Add(addCol);
    // Create DOB Column
    DataColumn dobCol = new DataColumn();
    dobCol.ColumnName= "DOB";
    dobCol.DataType = Type.GetType("System.DateTime");
    custTable.Columns.Add(dobCol);
    // VAR Column
    DataColumn fullTimeCol = new DataColumn();
    fullTimeCol.ColumnName= "VAR";
    fullTimeCol.DataType = Type.GetType("System.Boolean");
    custTable.Columns.Add(fullTimeCol);
    // Make the ID column the primary key column.
    DataColumn[] PrimaryKeyColumns = new DataColumn[1];
    PrimaryKeyColumns[0] = custTable.Columns["ID"];
    custTable.PrimaryKey = PrimaryKeyColumns;
    
    // Create a dataset
    DataSet ds = new DataSet("Customers");
    // Add Customers table to the dataset
    ds.Tables.Add(custTable); 
    // Attach the data set to a DataGrid
    dataGrid1.DataSource = ds.DefaultViewManager;
  }
}

Load Data to DataGrid

using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
public class LoadDataToDataGrid : System.Windows.Forms.Form
{
  private System.Windows.Forms.DataGrid dataGrid1;
  private System.Windows.Forms.Button button1;
  private System.ruponentModel.Container components = null;
  public LoadDataToDataGrid()
  {
    InitializeComponent();
  }
  protected override void Dispose( bool disposing )
  {
    if( disposing )
    {
      if (components != null) 
      {
        components.Dispose();
      }
    }
    base.Dispose( disposing );
  }
  private void InitializeComponent()
  {
    this.dataGrid1 = new System.Windows.Forms.DataGrid();
    this.button1 = new System.Windows.Forms.Button();
    ((System.ruponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
    this.SuspendLayout();
    this.dataGrid1.DataMember = "";
    this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
    this.dataGrid1.Location = new System.Drawing.Point(8, 8);
    this.dataGrid1.Name = "dataGrid1";
    this.dataGrid1.Size = new System.Drawing.Size(368, 240);
    this.dataGrid1.TabIndex = 0;
    this.button1.Location = new System.Drawing.Point(112, 264);
    this.button1.Name = "button1";
    this.button1.Size = new System.Drawing.Size(88, 32);
    this.button1.TabIndex = 1;
    this.button1.Text = "Fill";
    this.button1.Click += new System.EventHandler(this.button1_Click);
    // 
    // LoadDataToDataGrid
    // 
    this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
    this.ClientSize = new System.Drawing.Size(384, 302);
    this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                    this.button1,
                                    this.dataGrid1});
    this.Name = "LoadDataToDataGrid";
    this.Text = "LoadDataToDataGrid";
    ((System.ruponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
    this.ResumeLayout(false);
  }
  [STAThread]
  static void Main() 
  {
    Application.Run(new LoadDataToDataGrid());
  }
  private void button1_Click(object sender, System.EventArgs e)
  {
        string ConnectionString ="server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;";
        SqlConnection myConnection = new SqlConnection();
        myConnection.ConnectionString = ConnectionString;
        string sql = "SELECT ID, FirstName FROM Employee";
    SqlDataAdapter myAdapter = new SqlDataAdapter(sql, myConnection); 
        
        DataSet myDataSet = new DataSet("Employee");
        myAdapter.Fill(myDataSet, "Employee");
        dataGrid1.DataSource = myDataSet.DefaultViewManager;
  }
}

Programmatic Data Display

using System;
using System.Collections.Generic;
using System.ruponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Windows.Forms;

   class ProgrammaticDataDisplay : Form
   {
      public ProgrammaticDataDisplay()
      {
         InitializeComponent();
         string connectionString = "server=localhost;Trusted_Connection=yes; database=northwind";
         string commandString = "Select CompanyName, ContactName, ContactTitle, Phone, Fax from Customers";
         SqlDataAdapter DataAdapter = new SqlDataAdapter( commandString, connectionString );
         DataSet DataSet = new DataSet();
         DataAdapter.Fill( DataSet, "Customers" );
         dataGridView1.DataSource = DataSet.Tables["Customers"].DefaultView;
      }
      private void InitializeComponent()
      {
         this.dataGridView1 = new System.Windows.Forms.DataGridView();
         ( ( System.ruponentModel.ISupportInitialize ) ( this.dataGridView1 ) ).BeginInit();
         this.SuspendLayout();
         this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill;
         this.dataGridView1.Location = new System.Drawing.Point( 0, 0 );
         this.dataGridView1.Name = "dataGridView1";
         this.dataGridView1.Size = new System.Drawing.Size( 579, 262 );
         this.dataGridView1.TabIndex = 0;
         this.AutoScaleBaseSize = new System.Drawing.Size( 5, 13 );
         this.ClientSize = new System.Drawing.Size( 579, 262 );
         this.Controls.Add( this.dataGridView1 );
         this.Name = "ProgrammaticDataDisplay";
         this.Text = "Programmatic Data Display";
         ( ( System.ruponentModel.ISupportInitialize ) ( this.dataGridView1 ) ).EndInit();
         this.ResumeLayout( false );
      }

      private System.Windows.Forms.DataGridView dataGridView1;
      [STAThread]
      static void Main()
      {
         Application.Run( new ProgrammaticDataDisplay() );
      }
   }