Mega Code Archive

 
Categories / C# / ADO Database
 

Bind two DataGrids with many to many mapping

using System; using System.Drawing; using System.Collections; using System.ComponentModel; 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.Data.DataSet dataSet1;       private System.ComponentModel.Container components = null;       public Form1() {         InitializeComponent();       }       private void InitializeComponent(){         this.dataGrid1 = new System.Windows.Forms.DataGrid();         this.dataSet1 = new System.Data.DataSet();         ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();         ((System.ComponentModel.ISupportInitialize)(this.dataSet1)).BeginInit();         this.SuspendLayout();         this.dataGrid1.DataMember = "";         this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;         this.dataGrid1.Location = new System.Drawing.Point(0, 0);         this.dataGrid1.Name = "dataGrid1";         this.dataGrid1.Size = new System.Drawing.Size(400, 200);         this.dataGrid1.TabIndex = 0;         this.dataSet1.DataSetName = "NewDataSet";         this.dataSet1.Locale = new System.Globalization.CultureInfo("en-US");         this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);         this.ClientSize = new System.Drawing.Size(400, 196);         this.Controls.Add(this.dataGrid1);         this.Name = "Form1";         this.Text = "Form1";         this.Load += new System.EventHandler(this.Form1_Load);         ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();         ((System.ComponentModel.ISupportInitialize)(this.dataSet1)).EndInit();         this.ResumeLayout(false);       }       [STAThread]       static void Main() {         Application.Run(new Form1());       }       private void Form1_Load(object sender, System.EventArgs e) {          string connString = "server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI";          string qry1 = @"select * from employee ";          string qry2 = @"select * from order";          string sql = qry1 + qry2;          SqlConnection conn = new SqlConnection(connString);          SqlDataAdapter da = new SqlDataAdapter(sql, conn);               da.TableMappings.Add("Table", "employee");          da.TableMappings.Add("Table1", "order");          da.Fill(dataSet1);          DataRelation dr = new DataRelation(             "employeeorders",             dataSet1.Tables[0].Columns["employeeid"],              dataSet1.Tables[1].Columns["employeeid"]             );          dataSet1.Relations.Add(dr);          dataGrid1.SetDataBinding(dataSet1, "employees");       }     }