private bool SaveDataViewGridDatas() { bool isSave = false; try { List<Product> productLst = new List<Product>(); foreach (DataGridViewRow row in this.dgvProducts.Rows) { if (!row.IsNewRow) { int categoryId = Convert.ToInt32(row.Cells[0].Value); string categoryName = row.Cells[1].Value.ToString(); string productName = row.Cells[2].Value.ToString(); decimal productPrice = Convert.ToDecimal(row.Cells[3].Value); decimal productQty = Convert.ToDecimal(row.Cells[4].Value); Product product = new Product() { ProductName = productName, ProductPrice = productPrice, ProductQty = productQty, CategoryId = categoryId }; productLst.Add(product); } } if (InsertProductsBySP(productLst)) isSave = true; } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } return isSave; }
private bool InsertProduct(Product model) { bool isInsert = false; SqlConnection sqlConnection = null; try { string dbConnectionString = ConfigurationManager.ConnectionStrings["appConStr"].ConnectionString; sqlConnection = new SqlConnection(dbConnectionString); string sql = "INSERT INTO Product (ProductId, ProductName, ProductPrice, ProductQty, CategoryId) values (@ProductId, @ProductName, @ProductPrice, @ProductQty, @CategoryId)"; SqlCommand command = new SqlCommand(sql, sqlConnection); SqlParameter parmProductId = new SqlParameter("@ProductId", SqlDbType.Int); parmProductId.Value = model.ProductId; command.Parameters.Add(parmProductId); SqlParameter parmProductName = new SqlParameter("@ProductName", SqlDbType.NVarChar, 50); parmProductName.Value = model.ProductName; command.Parameters.Add(parmProductName); SqlParameter parmProductPrice = new SqlParameter("@ProductPrice", SqlDbType.Decimal); parmProductPrice.Value = model.ProductPrice; command.Parameters.Add(parmProductPrice); SqlParameter parmProductQty = new SqlParameter("@ProductQty", SqlDbType.Decimal); parmProductQty.Value = model.ProductQty; command.Parameters.Add(parmProductQty); SqlParameter parmCategoryId = new SqlParameter("@CategoryId", SqlDbType.Int); parmCategoryId.Value = model.CategoryId; command.Parameters.Add(parmCategoryId); sqlConnection.Open(); command.ExecuteNonQuery(); isInsert = true; } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } finally { if (sqlConnection.State == ConnectionState.Open) sqlConnection.Close(); } return isInsert; }