0% found this document useful (0 votes)
7 views16 pages

30 06

The document contains C# code for a product management system, defining two main classes: Category and Product, which include properties and methods for managing product data. It also includes forms for managing products, allowing users to add, edit, and delete products, as well as validate input data. The code utilizes Entity Framework for database operations and includes user interface elements for displaying and interacting with product information.

Uploaded by

ANH nguyen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views16 pages

30 06

The document contains C# code for a product management system, defining two main classes: Category and Product, which include properties and methods for managing product data. It also includes forms for managing products, allowing users to add, edit, and delete products, as well as validate input data. The code utilizes Entity Framework for database operations and includes user interface elements for displaying and interacting with product information.

Uploaded by

ANH nguyen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

 Category

using System.ComponentModel.DataAnnotations;

namespace QLBH.Models

internal class Category

public Category()

this.Products = new HashSet<Product>();

public long CategoryID { get; set; }

[StringLength(100)]

public string Name { get; set; }

public int Order { get; set; }

public bool Status { get; set; }

public virtual ICollection<Product> Products { get; set; }

 Product

using System.ComponentModel.DataAnnotations;

using System.ComponentModel.DataAnnotations.Schema;
namespace QLBH.Models

internal class Product

public long ProductID { get; set; }

[StringLength(200)]

public string Name { get; set; }

public int Quantity { get; set; }

[Column(TypeName = "decimal(18, 2)")]

public decimal Price { get; set; }

[Column(TypeName = "decimal(18, 2)")]

public decimal? MarketPrice { get; set; }[StringLength(1000)]

public string Description { get; set; }

[StringLength(200)]

public string? ImageFile { get; set; }

public bool Status { get; set; }

public long CategoryID { get; set; }

public virtual Category Category { get; set; }

 form quản lý sản phẩm


using QLBH.Models; namespace QLBH { public partial class fManageProduct :
Form { private long CategoryID; public fManageProduct()
{ InitializeComponent(); } private void fManageProduct_Load(object sender,
EventArgs e) { using (var db = new EFDbContext())
{ cbCategories.DisplayMember = "Name"; cbCategories.using QLBH.Models;

namespace QLBH

public partial class fManageProduct : Form

private long CategoryID;

public fManageProduct()

InitializeComponent();

private void fManageProduct_Load(object sender, EventArgs e)

using (var db = new EFDbContext())

cbCategories.DisplayMember = "Name";

cbCategories.ValueMember = "CategoryID";

cbCategories.DataSource = db.Categories.OrderBy(c =>

c.Order).Select(c => new { c.CategoryID, c.Name }).ToList();

dataGridView1.Width = ClientSize.Width - 10;

}
}

private void fManageProduct_Activated(object sender, EventArgs e)

cbCategories_SelectedIndexChanged(sender, e);

private void btFind_Click(object sender, EventArgs e)

using (var db = new EFDbContext())

if (ckCategory.Checked)

dataGridView1.DataSource = db.Products.Where(p =>

p.Name.Contains(txtName.Text) && (p.CategoryID == CategoryID ||

cbCategories.SelectedIndex < 0)).Select(p => new { p.ProductID, p.Name,

p.Quantity, p.Price, p.MarketPrice, p.Description, p.ImageFile, p.Status

}).ToList();

else

dataGridView1.DataSource = db.Products.Where(p =>

p.Name.Contains(txtName.Text)).Select(p => new { p.ProductID, p.Name,


p.Quantity,

p.Price, p.MarketPrice, p.Description, p.ImageFile, p.Status }).ToList();

private void btNew_Click(object sender, EventArgs e)


{

if (Utility.IsOpeningForm("fNewProduct"))

return;ValueMember = "CategoryID"; cbCategories.DataSource =


db.Categories.OrderBy(c => c.Order).Select(c => new { c.CategoryID,
c.Name }).ToList(); dataGridView1.Width = ClientSize.Width - 10; } } private
void fManageProduct_Activated(object sender, EventArgs e)
{ cbCategories_SelectedIndexChanged(sender, e); } private void
btFind_Click(object sender, EventArgs e) { using (var db = new EFDbContext()) {
if (ckCategory.Checked) dataGridView1.DataSource = db.Products.Where(p =>
p.Name.Contains(txtName.Text) && (p.CategoryID == CategoryID ||
cbCategories.SelectedIndex < 0)).Select(p => new { p.ProductID, p.Name,
p.Quantity, p.Price, p.MarketPrice, p.Description, p.ImageFile,
p.Status }).ToList(); else dataGridView1.DataSource = db.Products.Where(p =>
p.Name.Contains(txtName.Text)).Select(p => new { p.ProductID, p.Name,
p.Quantity, p.Price, p.MarketPrice, p.Description, p.ImageFile,
p.Status }).ToList(); } } private void btNew_Click(object sender, EventArgs e) { if
(Utility.IsOpeningForm("fNewProduct")) return;

fNewProduct f = new fNewProduct(); f.MdiParent = this.MdiParent; f.Show(); }


private void dataGridView1_CellContentClick(object sender,
DataGridViewCellEventArgs e) { if
(dataGridView1.Columns[e.ColumnIndex].Name == "Delete") { try { long
ProductID =
Convert.ToInt64(dataGridView1.Rows[e.RowIndex].Cells["ProductID"].Value);
using (var db = new EFDbContext()) { Product product = db.Products.Single(c =>
c.ProductID == ProductID); if (MessageBox.Show("Bạn muốn xóa sản phẩm " +
product.Name, "Xóa", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
== DialogResult.Yes) { db.Products.Remove(product); db.SaveChanges();
fManageProduct_Activated(sender, e); } } } catch (Exception ex)
{ MessageBox.Show("Lỗi, chưa xóa được? Error: " + ex.Message); } } if
(dataGridView1.Columns[e.ColumnIndex].Name == "Edit") { if
(Utility.IsOpeningForm("fEditProduct")) return; fEditProduct f = new
fEditProduct(Convert.ToInt64(dataGridView1.Rows[e.RowIndex].Cells["ProductI
D"].Va lue)); f.MdiParent = this.MdiParent; f.Show(); } } private void
cbCategories_SelectedIndexChanged(object sender, EventArgs e) { using (var db
= new EFDbContext()) { CategoryID =
Convert.ToInt64(cbCategories.SelectedValue); dataGridView1.DataSource =
db.Products.Where(p => p.CategoryID == CategoryID).Select(p => new
{ p.ProductID, p.Name, p.Quantity, p.Price, p.MarketPrice, p.Description,
p.ImageFile, p.Status }).ToList(); //lblNumOfProduct.Text = "Số sản phẩm: " +
dataGridView1.Rows.Count; } } private void dataGridView1_CellClick(object
sender, DataGridViewCellEventArgs e) { pictureBox1.ImageLocation =
Utility.ImagePath + dataGridView1.Rows[e.RowIndex].Cells["ImageFile"].Value;
} }}

 From nhập sản phẩm

using QLBH.Models;

namespace QLBH

public partial class fNewProduct : Form

private Product product;

public fNewProduct()

InitializeComponent();

private void fNewProduct_Load(object sender, EventArgs e)

mQuantity.ValidatingType = typeof(UInt64);
mPrice.ValidatingType = typeof(decimal);

mMarketPrice.ValidatingType = typeof(decimal);

using (var db = new EFDbContext())

cbCategories.DisplayMember = "Name";

cbCategories.ValueMember = "CategoryID";

cbCategories.DataSource = db.Categories.OrderBy(c =>

c.Order).Select(c => new { c.CategoryID, c.Name }).ToList(); //sau 2 lệnh trên

cbCategories.Text = null; //không hiển thị dữ liệu, nếu bỏ lệnh

này, sẽ hiển thị theo loại đầu tiên

//hoặc cbCategories.SelectedValue = "";//không thể đặt null;

private void btClose_Click(object sender, EventArgs e)

Close(); //nhớ thiết lập thuộc tính CausesValidation

private void btBrowse_Click(object sender, EventArgs e)

//Nhớ xóa trống thuộc tính Filename lúc thiết kế

//Filter có thể thiết lập lúc thiết kế

openFileDialog1.Filter = "All file|*.*|Bitmap

File|*.bmp;*.dib|JPEG|*.jpg;*.jpe;*.jpeg;*.jfif|GIF|*.gif|TIFF|*.tif;*.tiff|PNG|*
.png|ICO|*.ico";

if (openFileDialog1.ShowDialog() == DialogResult.OK)

txtImageFile.Text = openFileDialog1.FileName;

pictureBox1.ImageLocation = openFileDialog1.FileName;

private void btSave_Click(object sender, EventArgs e)

if (string.IsNullOrWhiteSpace(txtName.Text))

toolTip1.Show("Hãy nhập tên sản phẩm?", txtName, 0, 0, 1000);

txtName.Focus();

return;

if (string.IsNullOrWhiteSpace(cbCategories.Text))

toolTip1.Show("Hãy nhập loại sản phẩm?", cbCategories, 0, 0,

1000);

cbCategories.Focus();

return;

}
if (string.IsNullOrWhiteSpace(mQuantity.Text))

toolTip1.Show("Hãy nhập số lượng?", mQuantity, 0, 0, 1000);

mQuantity.Focus();

return;

if (string.IsNullOrWhiteSpace(mPrice.Text))

toolTip1.Show("Hãy nhập giá bán?", mPrice, 0, 0, 1000);

mPrice.Focus();

return;

try

product = new Product(); //Tạo một thể hiện cho sản phẩm mới

product.Name = txtName.Text;

product.Quantity = Convert.ToInt32(mQuantity.Text);

product.Price = Convert.ToDecimal(mPrice.Text);

product.MarketPrice =

string.IsNullOrWhiteSpace(mMarketPrice.Text) ? (decimal?)null :

Convert.ToDecimal(mMarketPrice.Text);

product.Description = rDescription.Text;

product.Status = ckStatus.Checked;
product.CategoryID = Convert.ToInt64(cbCategories.SelectedValue);

using (var db = new EFDbContext())

db.Products.Add(product); //Thêm sản phẩm vào bối cảnh

db.SaveChanges(); //Lưu các thay đổi vào csdl

//Lưu hình vào thư mục hình và tên tập tin hình vào csdl

if (!string.IsNullOrWhiteSpace(txtImageFile.Text))

string ext =

txtImageFile.Text.Substring(txtImageFile.Text.LastIndexOf("."),

txtImageFile.Text.Length - txtImageFile.Text.LastIndexOf("."));

product.ImageFile = product.ProductID + ext;

pictureBox1.Image.Save(Utility.ImagePath +

product.ProductID + ext);

db.SaveChanges(); //Lưu các thay đổi vào csdl

//Xóa trống và thiết lập lại các điều khiển

txtName.Text = null;

//cbCategories.Text = null;

mQuantity.Text = null;

mPrice.Text = null;

mMarketPrice.Text = null;
rDescription.Text = null;

ckStatus.Checked = true;

txtImageFile.Text = null;

pictureBox1.ImageLocation = null;

toolTip1.Show("Lưu thành công.", btSave, 0, 0, 1000);

catch (Exception ex)

toolTip1.Show("Lưu thất bại? Error: " + ex.Message, btSave, 0, 0,

1000);

txtName.Focus();

private void fNewProduct_FormClosing(object sender,


FormClosingEventArgs

e)

e.Cancel = false;

private void txtName_Validating(object sender,

System.ComponentModel.CancelEventArgs e)

if (string.IsNullOrWhiteSpace(txtName.Text))
{

toolTip1.Show("Hãy nhập tên khách hàng?", txtName, 0, 0, 1000);

e.Cancel = true;

else if (txtName.Text.Length > 200)

toolTip1.Show("Tên khách hàng <= 100 ký tự?", txtName, 0, 0,

1000);

e.Cancel = true;

private void txtImageFile_Validating(object sender,

System.ComponentModel.CancelEventArgs e)

pictureBox1.Image = null;

if (string.IsNullOrWhiteSpace(txtImageFile.Text))

return; //Không cần nhập dữ liệu cho cột có thể null

if (txtImageFile.Text.Length > 200)

toolTip1.Show("Tên tập tin - tối đa 200 ký tự?", txtImageFile, 0,

0, 1000);

e.Cancel = true;

}
else if (!File.Exists(txtImageFile.Text))

toolTip1.Show("Tên tập tin sai hoặc Tập tin không tồn tại?",

txtImageFile, 0, 0, 1000);

e.Cancel = true;

Else

pictureBox1.ImageLocation = txtImageFile.Text;

private void cbCategories_Validating(object sender,

System.ComponentModel.CancelEventArgs e)

if (cbCategories.FindStringExact(cbCategories.Text) < 0) //Nếu sai

tên loại

toolTip1.Show("Nhập sai loại sản phẩm?", cbCategories, 0, 0,

1000);

e.Cancel = true;

private void mQuantity_TypeValidationCompleted(object sender,

TypeValidationEventArgs e)

{
if (!e.IsValidInput) //Nếu nhập sai kiểu

toolTip1.Show("Dữ liệu sai kiểu số nguyên?", mQuantity, 0, 0,

1000);

e.Cancel = true;

else

if ((UInt64)e.ReturnValue < 0) //Nếu giá trị âm

toolTip1.Show("Số lượng phải >= 0?", mQuantity, 0, 0, 1000);

e.Cancel = true;

private void mPrice_TypeValidationCompleted(object sender,

TypeValidationEventArgs e)

if (!e.IsValidInput)

toolTip1.Show("Dữ liệu sai kiểu số thực?", mPrice, 0, 0, 1000);

e.Cancel = true;

else

if ((decimal)e.ReturnValue < 0)
{

toolTip1.Show("Giá phải >= 0?", mPrice, 0, 0, 1000);

e.Cancel = true;

private void mMarketPrice_TypeValidationCompleted(object sender,

TypeValidationEventArgs e)

if (string.IsNullOrWhiteSpace(mMarketPrice.Text))

return; //Không cần nhập dữ liệu cho cột có thể null

if (!e.IsValidInput)

toolTip1.Show("Dữ liệu sai kiểu số thực?", mMarketPrice, 0, 0,

1000);

e.Cancel = true;

else

if ((decimal)e.ReturnValue < 0)

toolTip1.Show("Giá phải >= 0?", mMarketPrice, 0, 0, 1000);

e.Cancel = true;

}
}

You might also like