Thứ Năm, 27 tháng 2, 2014

Minh họa tính kế thừa class trong C#

Bài 30. Minh họa sự kế thừa, minh họa tính chất private và public các trường dữ liệu trong quá trình kế thừa.

1. Tạo lớp tàu có cấu trúc

class tau
    {
        //Các trường dữ liệu
        public string hangsx;
        public int nhienlieu;

        //Khởi tạo mặc định
        public tau()
        {
            hangsx = "VinaLine";
            nhienlieu = 10;
        }
    }

2. Tạo lớp tàu chiến, kế thừa lớp tàu:

class tauchien:tau
    {   //Khai báo trường dữ liệu
        //2 trường private và 1 trường public, các trường khác kế thừa từ lớp tau
        //trường private là trường riêng, nên muốn truy cập đến
        //2 trường này cần phải định nghĩa hàm thuộc tính có chứa get và set
        //2 trường riêng này các lớp dẫn xuất không kế thừa được
        private string sung;
        private string dan;
        public string chieudai;

        //thuộc tính Sung để tác động đến trường sung
        public string Sung
        {
            set { sung = value; }
            get { return sung; }
        }

        //thuộc tính Dan để tác động đến trường dan
        public string Dan
        {
            set { dan = value; }
            get { return dan; }
        }

        //Khởi tạo giá trị mặc định của tàu chiến
        public tauchien()
        {
            sung = "12ly7";
            dan = "Lien thanh";
            chieudai = "100m";
        }
    }

3. Tạo lớp tàu chở hàng, kế thừa lớp tàu chiến

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ct24_kethua
{
    class tauchohang:tauchien
    {
        //Gồm 1 trường dữ liệu
        //Các dữ liệu khác kế thừa từ lớp tauchien
        public int noichuahang;
        public tauchohang()
    {
        noichuahang=1500;
    }

    }
}


4. Tại chương trình chính thực hiện

class Program
    {
        static void Main(string[] args)
        {
            tau a = new tau();
            tauchien b = new tauchien();
            tauchohang c = new tauchohang();
            Console.WriteLine("Tau thong thuong:");
            Console.WriteLine("Hang san xuat: {0}, Nhien lieu mac dinh {1}", a.hangsx, a.nhienlieu );
            Console.WriteLine("------------------------");
           
            //Lớp tàu chiến
            //Do trường sung va dan là 2 trường private nên muốn lấy dữ liệu phải thông qua 2 phương thức Sung và Dan
            //hangsx và nhienlieu kế thừa từ lớp tau sang
            Console.WriteLine("TAU CHIEN:");
            Console.WriteLine("Hang san xuat: {0}, Nhien lieu mac dinh {1}", b.hangsx,b.nhienlieu);
            Console.WriteLine("Sung: {0}, Dan: {1}", b.Sung, b.Dan);
            Console.WriteLine("Chieu dai: {0} ", b.chieudai);
            Console.WriteLine("------------------------");
           

            //Lớp tàu chở hàng
            //c.chieudai kế thừa từ lớp tàu chiến
            //c.nhienlieu và c.hangsx kế thừa bắc cầu thông qua lớp tàu chiến đến lớp tàu.
            Console.WriteLine("TAU CHO HANG:");
            Console.WriteLine("Hang san xuat: {0}, Nhien lieu mac dinh {1}", a.hangsx,c.nhienlieu);
            Console.WriteLine("Noi chua hang: {0}", c.noichuahang);
            Console.WriteLine("Chieu dai: {0} ", c.chieudai);
           
           
            Console.ReadKey();

        }

    }

Thứ Tư, 26 tháng 2, 2014

Lỗi 262 khi tạo CSDL mới trong SQL SERVER 2K8

Lỗi 262:
I get CREATE DATABASE permission denied in database ‘master’. (Microsoft SQL Server, Error: 262) when I try to create a new database.
Cách khắc phục:
Click Start –> All Programs –> SQL Server Management Studio Express
(Right Click –> Run as administrator)
Then Click “Yes” in Dialog box
Now you can Create the Database…
It really works..

Thứ Sáu, 21 tháng 2, 2014

7. Tạo lớp Presentation, lớp thao tác dữ liệu với người dùng



7. Tạo lớp Presentation, lớp thao tác dữ liệu với người dùng

- Tạo thư mục Presentation


- Giao diện chính của chương trình




using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace BookShop.PresentationLayer
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {

        }

        private void btnBooks_Click(object sender, EventArgs e)
        {
            frmBooks frm = new frmBooks();
            frm.ShowDialog();
        }

        private void btnOrders_Click(object sender, EventArgs e)
        {
            frmOrders frm = new frmOrders();
            frm.ShowDialog();
        }
    }
}

- Giao diện cập nhật dữ liệu sách:



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BookShop.BusinessLayer;
using BookShop.Entities;

namespace BookShop.PresentationLayer
{
    public partial class frmBooks : Form
    {
        public frmBooks()
        {
            InitializeComponent();
        }

        private void tsAddBook_Click(object sender, EventArgs e)
        {

        }    

        public void LoadBooks()
        {
            dgvBooks.DataSource = BookBLL.GetList();

            string[] columns = { "BookID","BookName","Author","Price"};

            Utilities.ControlFormat.DataGridViewFormat(dgvBooks, columns);

        }

        private void frmBooks_Load(object sender, EventArgs e)
        {
            LoadBooks();
        }

        private void txtSearch_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                dgvBooks.DataSource = BookBLL.GetListByName(txtSearch.Text);
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            frmUpdateBook frm = new frmUpdateBook();
            frm.ShowDialog();
            LoadBooks();
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            frmUpdateBook frm = new frmUpdateBook((int)dgvBooks.SelectedRows[0].Cells["BookID"].Value);
            frm.ShowDialog();
            LoadBooks();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            int bookID = (int)dgvBooks.SelectedRows[0].Cells["BookID"].Value;

            if (bookID > 0)
            {
                BookBLL bll = new BookBLL();
                Book bk = bll.GetBookByID(bookID);

                if (MessageBox.Show("Bạn có chắc chắn muốn xóa cuốn sách "+bk.BookName +" không?","Thông báo",MessageBoxButtons.YesNo,MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    if (bll.Delete(bk))
                    {
                        MessageBox.Show("Xóa thành công!");
                        LoadBooks();
                    }
                    else
                        MessageBox.Show("Có lỗi xảy ra!");
                }
            }
        }
    }
}


- Giao diện thêm/sửa sách:



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BookShop.BusinessLayer;
using BookShop.Entities;

namespace BookShop.PresentationLayer
{
    public partial class frmUpdateBook : Form
    {
        private int _bookID = 0;
        BookBLL bll = new BookBLL();

        public frmUpdateBook()
        {
            InitializeComponent();
        }

        public frmUpdateBook(int bookID)
        {
            InitializeComponent();
            this._bookID = bookID;

            Book bk = bll.GetBookByID(bookID);

            txtBookName.Text = bk.BookName;
            txtAuthor.Text = bk.Author;
            txtPrice.Text = bk.Price.ToString();
            numAmount.Value = bk.Amount;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (_bookID == 0)
            {
                Book bk = new Book(txtBookName.Text, txtAuthor.Text, (int)numAmount.Value, int.Parse(txtPrice.Text));
                if (bll.Insert(bk))
                {
                    MessageBox.Show("Thêm sách mới thành công!");
                    this.Close();
                }
                else MessageBox.Show("Có lỗi xảy ra!");
            }
            else
            {
                Book bk = new Book(_bookID,txtBookName.Text, txtAuthor.Text, (int)numAmount.Value, int.Parse(txtPrice.Text));

                if (bll.Update(bk))
                {
                    MessageBox.Show("Sửa đổi thông tin sách thành công!");
                    this.Close();
                }
                else MessageBox.Show("Có lỗi xảy ra!");
            }
        }

        private void Reset()
        {
            txtBookName.Text = "";
            txtAuthor.Text = "";
            txtPrice.Text = "";
            numAmount.Value = 1;
            txtBookName.Focus();
        }

        private void frmUpdateBook_Load(object sender, EventArgs e)
        {

        }
    }
}

- Giao diện hóa đơn bán sách



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BookShop.BusinessLayer;
using BookShop.Entities;
using System.Globalization;
using BookShop.Utilities;

namespace BookShop.PresentationLayer
{
    public partial class frmOrders : Form
    {
        OrderBLL bll = new OrderBLL();

        public frmOrders()
        {
            InitializeComponent();
        }

        private void btnHide_Click(object sender, EventArgs e)
        {
            panel1.Visible = false;
            btnShow.Visible = true;
        }

        private void btnShow_Click(object sender, EventArgs e)
        {
            panel1.Visible = true;
            btnShow.Visible = false;
        }

        private void txtSearch_KeyPress(object sender, KeyPressEventArgs e)
        {

        }

        private void txtSearch_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                dgvBooks.DataSource = BookBLL.GetListByName(txtSearch.Text);

                dgvBooks.Rows[0].Selected = true;
                txtQuantity.Focus();
            }
        }



        private void btnSelect_Click(object sender, EventArgs e)
        {
            SelectBook();
        }

        private int totalPrice = 0;
        private void SelectBook()
        {
            Book bk = (Book)dgvBooks.SelectedRows[0].DataBoundItem;

            DataRow row = dtDetail.NewRow();

            row["No"] = dtDetail.Rows.Count + 1;
            row["BookID"] = bk.BookID;
            row["BookName"] = bk.BookName;
            row["Quantity"] = txtQuantity.Text;
            row["Price"] = ControlFormat.ToFormatPrice(bk.Price);
            row["TotalPrice"] = ControlFormat.ToFormatPrice((bk.Price * int.Parse(txtQuantity.Text)));

            dtDetail.Rows.Add(row);

            dghOrderDetails.DataSource = dtDetail;
            dgvBooks.Columns["Price"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dghOrderDetails.Columns["TotalPrice"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dghOrderDetails.Columns["Price"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            string s = row["TotalPrice"].ToString().Replace(",","");

            totalPrice += int.Parse(s);

            txtTotalPrice.Text = ControlFormat.ToFormatPrice(totalPrice);

            txtSearch.Text = "";
            txtSearch.Focus();


        }

        DataTable dtDetail = new DataTable();

        private void frmOrders_Load(object sender, EventArgs e)
        {
            dtDetail.Columns.Add("No");
            dtDetail.Columns.Add("BookID");
            dtDetail.Columns.Add("BookName");
            dtDetail.Columns.Add("Quantity");
            dtDetail.Columns.Add("Price");          
            dtDetail.Columns.Add("TotalPrice");

            dgvOrders.DataSource = bll.GetListOrdersByDate(dtpOrderDate.Value);

            txtSearch.Focus();
           
        }

        private void txtSearch_TextChanged(object sender, EventArgs e)
        {

        }

        private void txtQuantity_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SelectBook();
            }
            else if (e.KeyCode == Keys.Tab)
                txtCustomerName.Focus();

        }

        private void btnPay_Click(object sender, EventArgs e)
        {
            Order od = new Order(txtCustomerName.Text,DateTime.Now, totalPrice);
            List<OrderDetail> listOD = new List<OrderDetail>();
            foreach (DataRow row in dtDetail.Rows)
            {
                OrderDetail d = new OrderDetail();
                d.OrderID = od.OrderID;
                d.BookID = int.Parse(row["BookID"].ToString());
                d.Quantity =int.Parse(row["Quantity"].ToString());
                d.Price = ControlFormat.ToIntPrice(row["Price"].ToString());
                d.TotalPrice = ControlFormat.ToIntPrice(row["TotalPrice"].ToString());
                listOD.Add(d);
            }
            od.ListOrderDetail = listOD;


           
            bll.InsertOrder(od);




            dgvOrders.DataSource = bll.GetListOrdersByDate(DateTime.Now);

            Reset();
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            Reset();
        }

        private void Reset()
        {
            dghOrderDetails.DataSource = null;
            dgvBooks.DataSource = null;
            dtDetail.Rows.Clear();

            totalPrice = 0;
            txtTotalPrice.Text = "";
            txtCustomerName.Text = "";
            txtSearch.Focus();
        }

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            OrderBLL bll = new OrderBLL();
            dgvOrders.DataSource = bll.GetListOrdersByDate(dtpOrderDate.Value);
        }
    }
}