using System; using System.Windows.Forms; using System.Drawing; using System.Data.SqlClient; public class ex : Form { private Button b1 = new Button(); private DataGridView dgv = new DataGridView(); int rw = 0; public ex() { Text = "hello"; Width = 400; b1.Text = "return"; b1.Click += new EventHandler(button_b1_click); b1.Location = new Point(200, 0); dgv.Location = new Point(0, 25); dgv.Height = 400; dgv.Width = 400; dgv.ColumnCount = 3; Controls.Add(b1); Controls.Add(dgv); } public void button_b1_click(object sender, EventArgs e) { SqlConnection conn = new SqlConnection("Data Source = (localdb)\\sql;" + "User id= sample_user;" + "Password = 'abc'; " + "Database = ex;"); conn.Open(); SqlCommand command = new SqlCommand( "select CustomerID, FirstName, LastName " + "from Customers ", conn); SqlDataReader reader = command.ExecuteReader(); dgv.Columns[0].Name = "CustomerID"; dgv.Columns[1].Name = "FirstName"; dgv.Columns[2].Name = "LastName"; while (reader.Read()) { dgv.Rows.Add(); dgv.Rows[rw].HeaderCell.Value = (rw + 1).ToString(); dgv.Rows[rw].Cells[0].Value = reader[0]; dgv.Rows[rw].Cells[1].Value = reader[1]; dgv.Rows[rw].Cells[2].Value = reader[2]; rw = rw + 1; } conn.Close(); } [STAThread] static public void Main() { Application.Run(new ex()); } }