public partial class Form1 : Form
{
private ProductDal _productDal = new ProductDal();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
dgwProducts.DataSource = _productDal.GetAll();
}
private void btnAdd_Click(object sender, EventArgs e)
{
_productDal.Add(new Product
{
Name = tbxName.Text,
UnitPrice = Convert.ToDecimal(tbxUnitPrice.Text),
StockAmount = Convert.ToInt32(tbxStockAmount.Text)
});
MessageBox.Show("Product added!");
}
}
public class ProductDal
{
private const string CONNECTION_STRING = @"server=(localdb)\mssqllocaldb;initial catalog=ETrade;integrated security=true";
private SqlConnection _connection = new SqlConnection(CONNECTION_STRING);
public List<Product> GetAll()
{
Connect();
SqlCommand command = new SqlCommand("SELECT * FROM Products", _connection);
SqlDataReader reader = command.ExecuteReader();
List<Product> products = new List<Product>();
while (reader.Read())
{
Product product = new Product
{
Id = Convert.ToInt32(reader["Id"]),
Name = reader["Name"].ToString(),
StockAmount = Convert.ToInt32(reader["StockAmount"]),
UnitPrice = Convert.ToDecimal(reader["UnitPrice"])
};
products.Add(product);
}
reader.Close();
_connection.Close();
return products;
}
public void Add(Product product)
{
Connect();
SqlCommand command = new SqlCommand("INSERT INTO Products (Name, UnitPrice, StockAmount) VALUES (@name, @unitprice, @stockamount)", _connection);
command.Parameters.AddWithValue("@name", product.Name);
command.Parameters.AddWithValue("@unitprice", product.UnitPrice);
command.Parameters.AddWithValue("@stockamount", product.StockAmount);
command.ExecuteNonQuery();
_connection.Close();
}
private void Connect()
{
if (_connection.State == ConnectionState.Closed)
{
_connection.Open();
}
}
}