Mega Code Archive

 
Categories / C# / ADO Database
 

Set DataSource from DataSet

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 {     const string strConnect = "data source=\".\";database='biblio';uid=\"admin\";pwd=pw";     string strQuery = "Select Title, Price from Titles where Title like 'Hit%'";     SqlConnection cn = new SqlConnection(strConnect); // = new SqlDataAdapter();     DataSet ds = new DataSet();     internal System.Windows.Forms.Button Button1;     internal System.Windows.Forms.DataGrid DataGrid1;     private System.Data.SqlClient.SqlDataAdapter da;     public Form1() {         this.Button1 = new System.Windows.Forms.Button();         this.DataGrid1 = new System.Windows.Forms.DataGrid();         this.da = new System.Data.SqlClient.SqlDataAdapter();         ((System.ComponentModel.ISupportInitialize)(this.DataGrid1)).BeginInit();         this.SuspendLayout();         this.Button1.Location = new System.Drawing.Point(168, 266);         this.Button1.Size = new System.Drawing.Size(96, 32);         this.Button1.Text = "Get Data";         this.Button1.Click += new System.EventHandler(this.Button1_Click);         this.DataGrid1.DataMember = "";         this.DataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;         this.DataGrid1.Location = new System.Drawing.Point(8, 18);         this.DataGrid1.Size = new System.Drawing.Size(392, 232);         this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);         this.ClientSize = new System.Drawing.Size(408, 317);         this.Controls.AddRange(new System.Windows.Forms.Control[] {                                                                           this.Button1,                                                                           this.DataGrid1});         this.Load += new System.EventHandler(this.Form1_Load);         ((System.ComponentModel.ISupportInitialize)(this.DataGrid1)).EndInit();         this.ResumeLayout(false);     }     [STAThread]     static void Main() {         Application.Run(new Form1());     }     private void Form1_Load(object sender, System.EventArgs e) {         try {             cn.Open();             da.SelectCommand = new SqlCommand(strQuery, cn);         } catch (SqlException ex) {             Console.WriteLine(ex.ToString());         }     }     private void Button1_Click(object sender, System.EventArgs e) {         da.Fill(ds, "Titles and Price");         DataGrid1.DataSource = ds.Tables["Titles and Price"];     } }