/*--------------------------------------------------------------------------- USING ADO IN CODE STEP 1 : Reading a SQL Table Ron Kessler Created 5/10/2007 For C# 2005 --------------------------------------------------------------------------- This demonstrates the 7 steps to connect a datagrid control to a SQL 2005 Express Database We create all the objects in code instead of using the controls from the toolbox Make sure to create the DB in Server Explorer or attach the DB if you download mine from the web. This project only reads a table and shows the data in the grid control. * * */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; //be sure to add this namespace ADO_SQL_in_Code_Part_1 { public partial class frmADOPart1 : Form { public frmADOPart1() { InitializeComponent(); } private void frmADOPart1_Load(object sender, EventArgs e) { GetData(); } private void GetData() { try { //---create the connection string string connString = "Data Source=localhost\\SQLEXPRESS;Initial Catalog=customers-05;Integrated Security=True"; //---now create the Connection object SqlConnection conn = new SqlConnection(connString); //---now create a SQL string to get records string mySQL = "SELECT * FROM Customers ORDER BY Name"; //---now make the data adapter SqlDataAdapter DA = new SqlDataAdapter(mySQL, conn); //---now make a Dataset DataSet myDS = new DataSet(); //---make it so! DA.Fill(myDS, "customers"); //---now tell the grid where to get the data dgCustomers.DataSource = myDS; dgCustomers.DataMember = "customers"; } catch (SqlException sqlError) { if (MessageBox.Show("An error occurred while reading the database." + sqlError.Message, "System Message", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error) == DialogResult.Retry) { GetData(); } else { this.Close(); } } } private void ExitToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } } }