public List<Product> GetAll() { SqlConnection con = new SqlConnection (@"Server=.\sqlexpress; Initial Catalog=ETrade; User Id=sa; Password=***;"); if (con.State==ConnectionState.Closed) { con.Open(); } SqlCommand sqlCommand = new SqlCommand("SELECT * FROM Products", con); SqlDataReader sqlDataReader= sqlCommand.ExecuteReader(); List<Product> products = new List<Product>(); while (sqlDataReader.Read()) { Product product = new Product() { Id = (Int32)sqlDataReader["Id"], Name = sqlDataReader["Name"].ToString(), UnitPrice = (decimal)sqlDataReader["UnitPrice"], StockAmount = (Int32)sqlDataReader["StockAmount"], }; products.Add(product); } return products; }
From Form
public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { IProductDal productDal = new ProductDal(); dgwProduct.DataSource=productDal.GetAll(); } }