<file_sep>﻿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 Service.Common.DB;
using Message.Model;
using Service.Common.Log;
using Service.Common;

namespace WinApp.WinForm.Report
{
    public partial class FormSaleDetail : Form
    {
        Sale SaleInfo = new Sale();
        public FormSaleDetail(Int32 sald_id)
        {
            InitializeComponent();
            dataGridView1.AutoGenerateColumns = false;
            LoadInfo(sald_id);
        }
        private void LoadInfo(Int32 SaleID)
        {
            SaleInfo.FindbyPK(SaleID.ToString());
            Text = SaleInfo.TradeNo;

            lbTradeNo.Text = SaleInfo.TradeNo;
            lbOrderNo.Text = SaleInfo.OrderNo;
            lbCustomer.Text = SaleInfo.Customer.ToString();
            lbStoreHouse_ID.Text = SaleInfo.StoreHouse_ID.ToString();
            lbSaleDate.Text = SaleInfo.SaleDate.ToString("yyyy年M月d日 HH:mm:ss");
            lbCheckoutTime.Text = SaleInfo.CheckoutTime.ToString("yyyy年M月d日 HH:mm:ss");
            tbxCash.Text = SaleInfo.Cash.ToString("f2");
            tbxUnionPay.Text = SaleInfo.UnionPay.ToString("f2");
            tbxMemCard.Text = SaleInfo.MemCard.ToString("f2");
            tbxOtherPayment.Text = SaleInfo.OtherPayment.ToString("f2");
            lbTotalAmount.Text = SaleInfo.TotalAmount.ToString("f2");
            if (SaleInfo.Account == "0000")
            {
                lbAccount.Text = "----";
            }
            else
            {
                lbAccount.Text = SaleInfo.Account;
            }
            ReturnMessage rm = new ReturnMessage();
            List<string[]> liWhere = new List<string[]>();
            liWhere.Add(new string[] { "CardNO = {0}", SaleInfo.Account });
            MemberCard mc = new MemberCard();
            DataTable dtmc = mc.GetDataSet("SELECT TOP 1 ID FROM MemberCard", liWhere);
            string MbID;
            if (dtmc.Rows.Count > 0)
            {
                MbID = dtmc.Rows[0][0].ToString();
                mc.FindbyPK(MbID);
                lbMbName.Text = mc.MemberName;
            }
            else
            {
                lbMbName.Text = "----";
            }
            liWhere.Clear();
            Employee emp = new Employee();
            emp.FindbyPK(SaleInfo.Employee_ID.ToString());
            lbEmployeeName.Text = emp.Name;



            List<string[]> where = new List<string[]>();
            List<string[]> order = new List<string[]>();
            where.Add(new string[] { "SaleOrder_ID = {0}", SaleID.ToString() });
            order.Add(new string[] { "a.Sale_Dtl_Time", "ASC" });
            DataTable dt = SaleInfo.GetDataSet("SELECT a.Sale_Detail_ID,b.Product_ID,b.Code,b.Name AS ProductName,convert(numeric(18,2),a.Price) AS PaidIn1,convert(numeric(18,2),b.Price) AS Price,convert(numeric(18,2),a.Quantity) AS Quantity,convert(numeric(18,2),a.Price/b.Price) AS Discount, convert(numeric(18,2),a.Price*a.Quantity) AS PaidInAmount,a.Employee_ID,c.Name AS ServerName FROM Sale_Detail a LEFT JOIN Product b ON b.Product_ID = a.Product_ID LEFT JOIN Employee c ON c.Employee_ID = a.Employee_ID", where, order);
            dataGridView1.DataSource = dt;
        }

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            if (e.RowIndex >= dataGridView1.FirstDisplayedScrollingRowIndex)
            {
                using (SolidBrush b = new SolidBrush(dataGridView1.RowHeadersDefaultCellStyle.ForeColor))
                {
                    int linen = 0;
                    linen = e.RowIndex + 1;
                    string line = linen.ToString();
                    e.Graphics.DrawString(line, e.InheritedRowStyle.Font, b, e.RowBounds.Location.X, e.RowBounds.Location.Y + 5);
                    SolidBrush B = new SolidBrush(Color.Red);
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btnPrintAgain_Click(object sender, EventArgs e)
        {
            DataSet ds = new DataSet();
            ds.Tables.Add(((DataTable)dataGridView1.DataSource).Copy());
            PrintCommon pc = new PrintCommon();
            pc.PrintDataSet(ds, SaleInfo);
        }

        private void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            Int32 selectRow = dataGridView1.CurrentCell.RowIndex;
            FormChangeWaiter fcw = new FormChangeWaiter(Convert.ToInt32(dataGridView1.Rows[selectRow].Cells["Sale_Detail_ID"].Value));
            if (fcw.ShowDialog() == DialogResult.OK)
            {
                MessageBox.Show("修改成功！");
                LoadInfo(SaleInfo.Sale_ID);
            }
            dataGridView1.CurrentCell = dataGridView1[0, selectRow];
        }

        private void btnSaveChange_Click(object sender, EventArgs e)
        {
            decimal TotalAmount = Convert.ToDecimal(tbxCash.Text) + Convert.ToDecimal(tbxUnionPay.Text) + Convert.ToDecimal(tbxMemCard.Text) + Convert.ToDecimal(tbxOtherPayment.Text);
            if (TotalAmount == Convert.ToDecimal(lbTotalAmount.Text))
            {
                if (Convert.ToDecimal(tbxMemCard.Text)!=SaleInfo.MemCard)
                {
                    decimal Adjustment = Convert.ToDecimal(tbxMemCard.Text) - SaleInfo.MemCard;
                    string CardNumber = SaleInfo.Account;
                    if (CardNumber == "0000")
                    {
                        FormMemCard fmc = new FormMemCard(Adjustment);
                        if (fmc.ShowDialog() == DialogResult.OK && fmc.PaymentCard == Adjustment)
                        {
                            CardNumber = fmc.CardNo;
                        }
                        else
                        {
                            MessageBox.Show("会员卡信息操作失败，未保存！");
                            return;
                        }
                    }
                    ReturnMessage rm = new ReturnMessage();
                    rm = MemCardOper.MemCardHandle(CardNumber, Adjustment, SaleInfo.TradeNo);
                    SaleInfo.Account = CardNumber;
                    if (!rm.IsSucessed)
                    {
                        MessageBox.Show("操作失败，" + rm.Message);
                        return;
                    }
                }


                SaleInfo.Cash = Convert.ToDecimal(tbxCash.Text);
                SaleInfo.UnionPay = Convert.ToDecimal(tbxUnionPay.Text);
                SaleInfo.MemCard = Convert.ToDecimal(tbxMemCard.Text);
                SaleInfo.OtherPayment = Convert.ToDecimal(tbxOtherPayment.Text);
                SaleInfo.Update();
                MessageBox.Show("保存成功！");
                Close();
            }
            else
            {
                MessageBox.Show("金额填写不正确！");
            }
        }

        private void tbxCash_KeyPress(object sender, KeyPressEventArgs e)
        {
            ControlCommon.VerDecimal(sender, e);
        }

        private void tbxUnionPay_KeyPress(object sender, KeyPressEventArgs e)
        {
            ControlCommon.VerDecimal(sender, e);
        }

        private void tbxMemCard_KeyPress(object sender, KeyPressEventArgs e)
        {
            ControlCommon.VerDecimal(sender, e);
        }

        private void tbxOtherPayment_KeyPress(object sender, KeyPressEventArgs e)
        {
            ControlCommon.VerDecimal(sender, e);
        }
    }
}<file_sep>﻿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 Service.Common;
using Message.Model;

namespace WinApp.WinForm.Report
{
    public partial class FormChangeWaiter : Form
    {
        Sale_Detail DetailInfo = new Sale_Detail();
        public FormChangeWaiter(Int32 Sale_Detail_ID)
        {
            InitializeComponent();
            ControlCommon.BindEmployee(cbWaiter);

            DetailInfo.FindbyPK(Sale_Detail_ID.ToString());
            cbWaiter.SelectedValue = DetailInfo.Employee_ID;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            DetailInfo.Employee_ID = Convert.ToInt32(cbWaiter.SelectedValue);
            DetailInfo.Update();
            DialogResult = DialogResult.OK;
        }
    }
}
<file_sep>﻿using System;
using Service.Common.Entity;
using System.Collections.Generic;
using System.Data;
namespace Message.Model
{
    /// <summary>
    /// Sale:实体类(属性说明自动提取数据库字段的描述信息)
    /// </summary>
    [TableAttribute("Sale")]
    public partial class Sale : EntityBase<Sale>
    {
        public Sale()
        { }
        #region Model
        private int _sale_id;
        private DateTime _saledate;
        private string _tradeno;
        private string _orderNo;
        private int _dept_id;
        private int _employee_id;
        private int _storehouse_id;
        private string _address;
        private string _account;
        private string _gatheringway;
        private int _customer;
        private decimal _totalAmount;
        private decimal _memCard;
        private decimal _cash;
        private decimal unionPay;
        private decimal _otherPayment;
        private DateTime _checkoutTime;
        private int _state = 1;
        /// <summary>
        /// 
        /// </summary>
        [PrimaryKey("Sale_ID", IsAuto = true)]
        public int Sale_ID
        {
            set { _sale_id = value; }
            get { return _sale_id; }
        }
        /// <summary>
        /// 
        /// </summary>
        [Property]
        public DateTime SaleDate
        {
            set { _saledate = value; }
            get { return _saledate; }
        }
        /// <summary>
        /// 单号
        /// </summary>
        [Property]
        public string TradeNo
        {
            set { _tradeno = value; }
            get { return _tradeno; }
        }
        /// <summary>
        /// 单号
        /// </summary>
        [Property]
        public string OrderNo
        {
            get { return _orderNo; }
            set { _orderNo = value; }
        }
        /// <summary>
        /// 部门ID
        /// </summary>
        [Property]
        public int Dept_ID
        {
            set { _dept_id = value; }
            get { return _dept_id; }
        }
        /// <summary>
        /// 操作员
        /// </summary>
        [Property]
        public int Employee_ID
        {
            set { _employee_id = value; }
            get { return _employee_id; }
        }
        /// <summary>
        /// 房间号
        /// </summary>
        [Property]
        public int StoreHouse_ID
        {
            set { _storehouse_id = value; }
            get { return _storehouse_id; }
        }
        /// <summary>
        /// 地址
        /// </summary>
        [Property]
        public string Address
        {
            set { _address = value; }
            get { return _address; }
        }
        /// <summary>
        /// 会员卡号
        /// </summary>
        [Property]
        public string Account
        {
            set { _account = value; }
            get { return _account; }
        }
        /// <summary>
        /// 采集方式
        /// </summary>
        [Property]
        public string GatheringWay
        {
            set { _gatheringway = value; }
            get { return _gatheringway; }
        }
        /// <summary>
        /// 金额
        /// </summary>
        [Property]
        public decimal TotalAmount
        {
            get { return _totalAmount; }
            set { _totalAmount = value; }
        }
        /// <summary>
        /// 会员卡支付额
        /// </summary>
        [Property]
        public decimal MemCard
        {
            get { return _memCard; }
            set { _memCard = value; }
        }
        /// <summary>
        /// 现金支付额
        /// </summary>
        [Property]
        public decimal Cash
        {
            get { return _cash; }
            set { _cash = value; }
        }
        /// <summary>
        /// 银联卡
        /// </summary>
        [Property]
        public decimal UnionPay
        {
            get { return unionPay; }
            set { unionPay = value; }
        }
        /// <summary>
        /// 其他支付方式
        /// </summary>
        [Property]
        public decimal OtherPayment
        {
            get { return _otherPayment; }
            set { _otherPayment = value; }
        }
        /// <summary>
        /// 顾客手牌号
        /// </summary>
        [Property]
        public int Customer
        {
            set { _customer = value; }
            get { return _customer; }
        }
        /// <summary>
        /// 结帐时间
        /// </summary>
        [Property]
        public DateTime CheckoutTime
        {
            get { return _checkoutTime; }
            set { _checkoutTime = value; }
        }
        /// <summary>
        /// 状态 0：已结帐，1：进行中
        /// </summary>
        [Property]
        public int State
        {
            set { _state = value; }
            get { return _state; }
        }
        #endregion Model


        /// <summary>
        /// 生成单号
        /// </summary>
        /// <returns></returns>
        public string getTradCode()
        {
            List<string[]> where = new List<string[]>();
            List<string[]> order = new List<string[]>();
            string Today = DateTime.Now.ToString("yyyyMMdd");
            where.Add(new string[] { "SaleDate >= {0}", Today });
            order.Add(new string[] { "TradeNo", "DESC" });
            DataTable dt = this.GetDataSet("SELECT TradeNo FROM Sale", where, order);
            if (dt.Rows.Count > 0)
            {
                return Today + (Convert.ToInt32(dt.Rows[0][0].ToString().Substring(8, 3)) + 1).ToString("000");
            }
            else
            {
                return Today + "001";
            }
        }

    }
    public class PaymentInfo
    {
        private decimal totalAmount = 0;
        private decimal memCard = 0;
        private decimal cash = 0;
        private decimal unionPay = 0;
        private decimal otherPayment = 0;
        private string account = "0000";

        /// <summary>
        /// 全单总计金额
        /// </summary>
        public decimal TotalAmount
        {
            get { return totalAmount; }
            set { totalAmount = value; }
        }
        /// <summary>
        /// 会员卡支付额
        /// </summary>
        public decimal MemCard
        {
            get { return memCard; }
            set { memCard = value; }
        }
        /// <summary>
        /// 现金
        /// </summary>
        public decimal Cash
        {
            get { return cash; }
            set { cash = value; }
        }
        /// <summary>
        /// 银联
        /// </summary>
        public decimal UnionPay
        {
            get { return unionPay; }
            set { unionPay = value; }
        }
        /// <summary>
        /// 其他支付方式
        /// </summary>
        public decimal OtherPayment
        {
            get { return otherPayment; }
            set { otherPayment = value; }
        }
        /// <summary>
        /// 会员卡号
        /// </summary>
        public string Account
        {
            get { return account; }
            set { account = value; }
        }
    }
}

<file_sep>﻿using System;
using Service.Common.Entity;
namespace Message.Model
{
	/// <summary>
	/// ProductUnit:实体类(属性说明自动提取数据库字段的描述信息)
	/// </summary>
    [TableAttribute("ProductUnit")]
    public partial class ProductUnit : EntityBase<ProductUnit>
	{
		public ProductUnit()
		{}
		#region Model
		private int _productunit_id;
		private string _name;
		private int _employee_id;
		private DateTime _createdate= DateTime.Now;
		private string _remark;
		/// <summary>
		/// 
        /// </summary>
        [PrimaryKey("ProductUnit_ID", IsAuto = true)]
		public int ProductUnit_ID
		{
			set{ _productunit_id=value;}
			get{return _productunit_id;}
		}
		/// <summary>
		/// 单位名称
        /// </summary>
        [Property]
		public string Name
		{
			set{ _name=value;}
			get{return _name;}
		}
		/// <summary>
		/// 
        /// </summary>
        [Property]
		public int Employee_ID
		{
			set{ _employee_id=value;}
			get{return _employee_id;}
		}
		/// <summary>
		/// 创建时间
        /// </summary>
        [Property]
		public DateTime CreateDate
		{
			set{ _createdate=value;}
			get{return _createdate;}
		}
		/// <summary>
		/// 
        /// </summary>
        [Property]
		public string Remark
		{
			set{ _remark=value;}
			get{return _remark;}
		}
		#endregion Model

	}
}

<file_sep>﻿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 System.Security.Principal;
using System.Threading;
using Message.Model;
using WinApp.Controls;
using WinApp.WinForm.Report;
using WinApp.WinForm.Admin;
using Service.Common;

namespace WinApp.WinForm
{
    public partial class MainForm : Form
    {
        const int AW_VER_NEGATIVE = 0x0008;
        const int AW_CENTER = 0x0010;
        const int AW_HIDE = 0x10000;

        Sale sale = new Sale();
        public MainForm()
        {
            InitializeComponent();
        }

        private void btnBilling_Click(object sender, EventArgs e)
        {
            OpenSale(0);
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("确定要退出程序吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) == DialogResult.No)
            {
                e.Cancel = true;
            }
            else
            {
                AnimateWindow(this.Handle, 1000, AW_CENTER | AW_HIDE | AW_VER_NEGATIVE);
                System.Environment.Exit(0);
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            FormLogin frmLogin = new FormLogin();
            DialogResult dr = frmLogin.ShowDialog();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要退出程序吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) == DialogResult.Yes)
            {
                AnimateWindow(this.Handle, 1000, AW_CENTER | AW_HIDE | AW_VER_NEGATIVE);
                System.Environment.Exit(0);
            }
        }
        private void BindListView()
        {
            flowLayoutPanel1.Controls.Clear();
            List<string[]> where = new List<string[]>();
            List<string[]> order = new List<string[]>();
            where.Add(new string[] { "State = {0}", "1" });
            order.Add(new string[] { "Customer", "ASC" });
            DataTable dt = sale.GetDataSet("SELECT * FROM Sale", where, order);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                UCCustomer btn = new UCCustomer();
                btn.Text = dt.Rows[i]["Customer"].ToString();
                btn.SaleID = Convert.ToInt32(dt.Rows[i]["Sale_ID"].ToString());
                btn.CustemerNo = dt.Rows[i]["Customer"].ToString();
                btn.StoreHouse_ID = dt.Rows[i]["StoreHouse_ID"].ToString();
                btn.Employee_ID = dt.Rows[i]["Employee_ID"].ToString();
                btn.SaleDate = Convert.ToDateTime(dt.Rows[i]["SaleDate"]);
                btn.Margin = new Padding(8);
                btn.MyEvent += new EventEntrust(btn_MyEvent);
                flowLayoutPanel1.Controls.Add(btn);
            }
        }

        void btn_MyEvent(object sender, int e)
        {
            OpenSale(e);
        }

        private void OpenSale(Int32 SaleID)
        {
            FormSale fs1 = new FormSale(this, SaleID);
            fs1.Show();
            this.Hide();
        }

        private void MainForm_VisibleChanged(object sender, EventArgs e)
        {
            BindListView();
            lbCurDate.Text = DateTime.Now.ToString("yyyy年M月d日 ") + DateTimeCommon.getWeek(Convert.ToInt32(DateTime.Now.DayOfWeek)) + " 农历：" + DateTimeCommon.GetChineseDate(DateTime.Now);
            Employee emp = new Employee();
            emp.FindbyPK(Thread.CurrentPrincipal.Identity.Name);
            lbCurUser.Text = emp.Name;
            timer1.Start();
            if (emp.Dept_ID != 0)
            {
                btnMaintain.Enabled = false;
                btnReportForm.Enabled = false;
            }
            else
            {
                btnMaintain.Enabled = true;
                btnReportForm.Enabled = true;
            }
        }

        private void btnStatistics_Click(object sender, EventArgs e)
        {
            FormSaleList fsl = new FormSaleList();
            fsl.ShowDialog();
        }

        private void btnMaintain_Click(object sender, EventArgs e)
        {
            FormAdmin fa = new FormAdmin();
            fa.ShowDialog();
        }

        private void btnSetting_Click(object sender, EventArgs e)
        {
            FormSetting fst = new FormSetting();
            fst.ShowDialog();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            lbCurrentTime.Text = DateTime.Now.ToString("HH:mm:ss:ff");
        }

        private void btnMembershipCard_Click(object sender, EventArgs e)
        {
            FormMembershipCard fmc = new FormMembershipCard();
            fmc.ShowDialog();
        }

        private void btnBackup_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("要开始备份数据吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) == DialogResult.Yes)
            {
                string strPath = Environment.CurrentDirectory + "\\Backup\\";
                FormDataBackup fdb = new FormDataBackup(strPath);
                if (fdb.ShowDialog() == DialogResult.OK)
                {
                    MessageBox.Show("备份成功！");
                    System.Diagnostics.Process.Start("Explorer.exe", strPath);
                }
                else
                {
                    MessageBox.Show("备份失败！" + fdb.Rm.Message);
                }
            }
        }

        private void btnReLogin_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("要退出当前帐号并重新登录吗？", "重新登录", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) == DialogResult.Yes)
            {
                FormLogin fl = new FormLogin();
                Hide();
                if (fl.ShowDialog() == DialogResult.OK)
                {
                    Show();
                }
            }
        }

        private void btnReportForm_Click(object sender, EventArgs e)
        {
            FormReport fr = new FormReport();
            fr.ShowDialog();
        }

        private void btnShift_Click(object sender, EventArgs e)
        {
            FormShift fs = new FormShift(0);
            fs.ShowDialog();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            test ts = new test();
            ts.ShowDialog();
        }

        [System.Runtime.InteropServices.DllImport("user32")]
        private static extern bool AnimateWindow(IntPtr hwnd, int dwTime, int dwFlags);
    }
}
<file_sep>﻿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 Service.Common;
using Message.Model;

namespace WinApp.WinForm.Admin
{
    public partial class FormAddDiscount : Form
    {
        public FormAddDiscount()
        {
            InitializeComponent();
        }

        private void tbxDiscountRate_KeyPress(object sender, KeyPressEventArgs e)
        {
            ControlCommon.VerDecimal(sender, e);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (tbxDisName.Text == "")
            {
                MessageBox.Show("请填写名称！");
                tbxDisName.Focus();
                return;
            }
            if (tbxDiscountRate.Text == "")
            {
                MessageBox.Show("请填写折扣！");
                tbxDiscountRate.Focus();
                return;
            }
            Discount dsc = new Discount();
            dsc.DisName = tbxDisName.Text;
            dsc.DiscountRate = Convert.ToDecimal(tbxDiscountRate.Text);
            if (rbAvailable.Checked)
            {
                dsc.Available = true;
            }
            else
            {
                dsc.Available = false;
            }
            dsc.Remark = "";
            dsc.Insert();
            MessageBox.Show("保存成功！");
            Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Message.Model;
using System.Data;

namespace Service.Common
{
    public static class ControlCommon
    {
        /// <summary>
        /// 绑定折扣
        /// </summary>
        /// <param name="cb"></param>
        public static void BindDiscount(ComboBox cb)
        {
            Discount dsc = new Discount();
            List<string[]> liWhere = new List<string[]>();
            List<string[]> liOrder = new List<string[]>();
            liWhere.Add(new string[] { "Available = '{0}'", "True" });
            liOrder.Add(new string[] { "DiscountRate", "DESC" });
            DataTable dt = dsc.GetDataSet("SELECT DiscountRate, DisName FROM Discount", liWhere, liOrder);
            cb.DisplayMember = "DisName";
            cb.ValueMember = "DiscountRate";
            cb.DataSource = dt;
            cb.SelectedIndex = 0;
        }
        /// <summary>
        /// 绑定会员卡类型
        /// </summary>
        /// <param name="cb"></param>
        public static void BindCardType(ComboBox cb)
        {
            CardType ct = new CardType();
            List<string[]> liWhere = new List<string[]>();
            List<string[]> liOrder = new List<string[]>();
            liWhere.Add(new string[] { "Available = '{0}'", "1" });
            liOrder.Add(new string[] { "ID", "ASC" });
            DataTable dt = ct.GetDataSet("SELECT ID, TypeName FROM CardType", liWhere, liOrder);
            cb.DisplayMember = "TypeName";
            cb.ValueMember = "ID";
            cb.DataSource = dt;
            cb.SelectedIndex = 0;
        }

        /// <summary>
        /// 绑定人员
        /// </summary>
        /// <param name="cb"></param>
        public static void BindEmployee(ComboBox cb)
        {
            Employee emp = new Employee();
            List<string[]> liWhere = new List<string[]>();
            List<string[]> liOrder = new List<string[]>();
            liWhere.Add(new string[] { "1 = '{0}'", "1" });
            liOrder.Add(new string[] { "Employee_ID", "DESC" });
            DataTable dt = emp.GetDataSet("SELECT Employee_ID, Name FROM Employee", liWhere, liOrder);
            cb.DisplayMember = "Name";
            cb.ValueMember = "Employee_ID";
            cb.DataSource = dt;
        }



        /// <summary>
        /// 绑定商品名
        /// </summary>
        /// <param name="cb"></param>
        public static void BindProduct(ComboBox cb)
        {
            Product emp = new Product();
            List<string[]> liWhere = new List<string[]>();
            List<string[]> liOrder = new List<string[]>();
            liWhere.Add(new string[] { "1 = '{0}'", "1" });
            liOrder.Add(new string[] { "Product_ID", "DESC" });
            DataTable dt = emp.GetDataSet("SELECT Product_ID, Name FROM Product", liWhere, liOrder);
            cb.DisplayMember = "Name";
            cb.ValueMember = "Product_ID";
            cb.DataSource = dt;
        }


        /// <summary>
        /// 正整数和负整数
        /// </summary>
        /// <param name="tb"></param>
        /// <param name="e"></param>
        public static void VerDigitalHL(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)13 && e.KeyChar != (char)8 && e.KeyChar != (char)45)
            {
                e.Handled = true;
            }
            else
            {
                if (e.KeyChar == (char)45)
                {
                    if (((TextBox)sender).Text.StartsWith("-"))
                    {
                        e.Handled = true;
                    }
                }
            }
        }

        /// <summary>
        /// 只能输入正整数
        /// </summary>
        /// <param name="e"></param>
        public static void VerDigital(KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)13 && e.KeyChar != (char)8)
            {
                e.Handled = true;
            }
        }

        /// <summary>
        /// 只能输入两位小数的数字
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void VerDecimal(object sender, KeyPressEventArgs e)
        {
            //判断按键是不是要输入的类型。
            if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && (int)e.KeyChar != 8 && (int)e.KeyChar != 46)
            {
                e.Handled = true;  //小数点的处理。
            }
            //else
            //{
            //    if ((int)e.KeyChar != 8)
            //    {
            //        if (((TextBox)sender).Text.Contains("."))
            //        {
            //            string[] SectionText = ((TextBox)sender).Text.Split(new char[] { '.' });
            //            if (SectionText[1].Length > 1)
            //            {
            //                e.Handled = true;
            //            }
            //        }

            //    }
            //}
            if ((int)e.KeyChar == 46)                           //小数点
            {
                if (((TextBox)sender).Text.Length <= 0)
                { e.Handled = true; }   //小数点不能在第一位
                else
                {
                    float f;
                    float oldf;
                    bool b1 = false, b2 = false;
                    b1 = float.TryParse(((TextBox)sender).Text, out oldf);
                    b2 = float.TryParse(((TextBox)sender).Text + e.KeyChar.ToString(), out f);
                    if (b2 == false)
                    {
                        if (b1 == true)
                        { e.Handled = true; }
                        else
                        { e.Handled = false; }
                    }
                }
            }
        }
    }
}
<file_sep>﻿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 Service.Common.Data;
using Message.Model;
using Service.Common;
using System.Threading;

namespace WinApp.WinForm
{
    public partial class FormSelect : Form
    {
        Product emp = new Product();
        SaleDtlInfo saleInfo = new SaleDtlInfo();
        public SaleDtlInfo SaleInfo
        {
            get { return saleInfo; }
            set { saleInfo = value; }
        }
        public FormSelect()
        {
            InitializeComponent();
            dataGridView1.AutoGenerateColumns = false;
            ControlCommon.BindDiscount(cbDiscount);
            BindProData();
            ControlCommon.BindEmployee(cbServer);
            DataTable dt = (DataTable)cbServer.DataSource;
            DataRow dr = dt.NewRow();
            dr["Employee_ID"] = 0;
            dr["Name"] = "<—请选择—>";
            dt.Rows.InsertAt(dr, 0);
            cbServer.SelectedIndex = 0;
        }

        private void BindProData()
        {
            List<string[]> where = new List<string[]>();
            if (!string.IsNullOrEmpty(tbxCode.Text.Trim()))
            {
                where.Add(new string[] { "Code LIKE '%' + {0} + '%'", tbxCode.Text.Trim() });
            }
            if (!string.IsNullOrEmpty(tbxPinYin.Text.Trim()))
            {
                where.Add(new string[] { "(spell LIKE '%' + {0} + '%' OR s_spell LIKE '%' + {0} + '%')", tbxPinYin.Text.Trim() });
            }

            DataTable dt = emp.GetDataSet("SELECT * FROM Product", where);
            dataGridView1.DataSource = dt;
        }
        private void tbxNo_TextChanged(object sender, EventArgs e)
        {
            BindProData();
            CalcAmount();
        }

        private void tbxPinYin_TextChanged(object sender, EventArgs e)
        {
            BindProData();
            CalcAmount();
        }

        private void cbDiscount_SelectionChangeCommitted(object sender, EventArgs e)
        {
            CalcAmount();
        }

        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            CalcAmount();
        }

        private void CalcAmount()
        {
            if (((DataTable)(dataGridView1.DataSource)).Rows.Count > 0 && tbxQty.Text.Length > 0 && tbxQty.Text != "-")
            {
                decimal Price = Convert.ToDecimal(dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells["Price"].Value);
                decimal Amount = Price * Convert.ToDecimal(cbDiscount.SelectedValue) * Convert.ToInt32(tbxQty.Text);
                lbAmount.Text = Math.Round(Amount, 2).ToString();
                //lbAmount.Text = ((Int32)((double)Amount + 0.5)).ToString();
            }
            else
            {
                lbAmount.Text = "--";
            }
        }

        private void tbxQty_TextChanged(object sender, EventArgs e)
        {
            CalcAmount();
        }

        private void tbxQty_KeyPress(object sender, KeyPressEventArgs e)
        {
            ControlCommon.VerDigitalHL(sender, e);
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void btnDetermine_Click(object sender, EventArgs e)
        {
            if (cbServer.SelectedValue.ToString() != "0")
            {
                if (dataGridView1.Rows.Count > 0 && lbAmount.Text != "--")
                {
                    if (Convert.ToDecimal(lbAmount.Text) >= 0)
                    {
                        SetSaleInfo();
                    }
                    else
                    {
                        if (new FormBackPassword().ShowDialog() == DialogResult.OK)
                        {
                            SetSaleInfo();
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("请选择服务人员！");
            }
        }

        private void SetSaleInfo()
        {
            SaleInfo.ProID = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells["ProID"].Value);
            SaleInfo.ProCode = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells["Code"].Value.ToString();
            SaleInfo.ProName = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells["ProName"].Value.ToString();
            SaleInfo.Price = Convert.ToDecimal(dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells["Price"].Value);
            SaleInfo.PaidIn = Convert.ToDecimal(lbAmount.Text);
            SaleInfo.Quanity = Convert.ToDecimal(tbxQty.Text);
            SaleInfo.Discount = Convert.ToDecimal(cbDiscount.SelectedValue);
            SaleInfo.Total = Convert.ToDecimal(dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells["Price"].Value) * Convert.ToDecimal(cbDiscount.SelectedValue);
            SaleInfo.ServerID = Convert.ToInt32(cbServer.SelectedValue);
            saleInfo.Sale_Dtl_Time = DateTime.Now;
            saleInfo.Server = cbServer.Text;
            this.DialogResult = DialogResult.OK;
        }

        private void tbxServicePerson_KeyPress(object sender, KeyPressEventArgs e)
        {
            ControlCommon.VerDigital(e);
        }
    }
}
<file_sep>﻿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 Message.Model;
using Service.Common;
using System.Threading;

namespace WinApp.WinForm.Report
{
    public partial class FormReport : Form
    {
        Sale SaleInfo = new Sale();
        public FormReport()
        {
            InitializeComponent();
            dgvSummary.AutoGenerateColumns = false;
            dgvDetail.AutoGenerateColumns = false;
        }

        private void FormReport_Load(object sender, EventArgs e)
        {
            updgvSummary.DataSetSql = "SELECT * FROM v_SaleList";
            updgvSummary.LiWhere.Add(new string[] { "State = {0}", "0" });
            updgvSummary.LiOrder.Add(new string[] { "Sale_ID", "DESC" });
            dgvSummary.DataSource = updgvSummary.GetDataTable();
            updgvSummary.PageEvent += new WinApp.Controls.PageEntrust(updgvSummary_PageEvent);
            updgvDetail.PageEvent += new WinApp.Controls.PageEntrust(updgvDetail_PageEvent);
            GetTotalAmount();
            ControlCommon.BindEmployee(cbServer);
            DataTable dt = (DataTable)cbServer.DataSource;
            DataRow dr = dt.NewRow();
            dr["Employee_ID"] = 0;
            dr["Name"] = "<—全部—>";
            dt.Rows.InsertAt(dr, 0);
            cbServer.SelectedIndex = 0;
            ControlCommon.BindProduct(cbProName);
            DataTable dt1 = (DataTable)cbProName.DataSource;
            DataRow dr1 = dt1.NewRow();
            dr1["Product_ID"] = 0;
            dr1["Name"] = "<—全部—>";
            dt1.Rows.InsertAt(dr1, 0);
            cbProName.SelectedIndex = 0;
        }

        void updgvSummary_PageEvent()
        {
            dgvSummary.DataSource = updgvSummary.GetDataTable();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            updgvSummary.LiWhere.Clear();
            updgvSummary.LiWhere.Add(new string[] { "State = {0}", "0" });
            if (dtpFrom.Checked)
            {
                updgvSummary.LiWhere.Add(new string[] { "CheckoutTime > {0}", dtpFrom.Value.ToShortDateString() });
            }
            if (dtpTo.Checked)
            {
                updgvSummary.LiWhere.Add(new string[] { "CheckoutTime < {0}", dtpTo.Value.AddDays(1).ToShortDateString() });
            }
            if (tbxTradCode.Text.Trim() != "")
            {
                updgvSummary.LiWhere.Add(new string[] { "TradeNo LIKE '%' + {0} + '%'", tbxTradCode.Text.Trim() });
            }
            if (tbxOrderNo.Text.Trim() != "")
            {
                updgvSummary.LiWhere.Add(new string[] { "OrderNo LIKE '%' + {0} + '%'", tbxOrderNo.Text.Trim() });
            }
            updgvSummary.CurPage = 1;
            dgvSummary.DataSource = updgvSummary.GetDataTable();
            GetTotalAmount();
        }
        private void GetTotalAmount()
        {
            DataTable dt = SaleInfo.GetDataSet("SELECT SUM(TotalAmount) FROM v_SaleList", updgvSummary.LiWhere);
            if (dt.Rows[0][0] != System.DBNull.Value)
            {
                lbTotalAmount.Text = (Convert.ToDecimal(dt.Rows[0][0])).ToString("f2") + " 元";
            }
            else
            {
                lbTotalAmount.Text = "0 元";
            }
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            FormExport fe = new FormExport(updgvSummary);
            fe.ShowDialog();
        }

        private void tabPage2_Enter(object sender, EventArgs e)
        {
            updgvDetail.LiOrder.Clear();
            updgvDetail.LiWhere.Clear();
            updgvDetail.LiOrder.Add(new string[] { "Sale_Detail_ID", "DESC" });
            updgvDetail.LiWhere.Add(new string[] { "State = {0}", "0" });
            updgvDetail.DataSetSql = "SELECT * FROM v_SaleDetailList";
            dgvDetail.DataSource = updgvDetail.GetDataTable();
            GetDtlTotalAmount();
        }

        void updgvDetail_PageEvent()
        {
            dgvDetail.DataSource = updgvDetail.GetDataTable();
        }

        private void GetDtlTotalAmount()
        {
            DataTable dt = SaleInfo.GetDataSet("SELECT SUM(Total),SUM(Commission) FROM v_SaleDetailList", updgvDetail.LiWhere);
            if (dt.Rows[0][0] != System.DBNull.Value)
            {
                lbDtlTotalAmount.Text = (Convert.ToDecimal(dt.Rows[0][0])).ToString("f2") + " 元";
                lbCommission.Text = (Convert.ToDecimal(dt.Rows[0][1])).ToString("f2") + " 元";
            }
            else
            {
                lbDtlTotalAmount.Text = "0 元";
                lbCommission.Text = "0 元";
            }
        }

        private void btnDtlSearch_Click(object sender, EventArgs e)
        {
            updgvDetail.LiWhere.Clear();
            updgvDetail.LiWhere.Add(new string[] { "State = {0}", "0" });
            if (dtpDtlFrom.Checked)
            {
                updgvDetail.LiWhere.Add(new string[] { "CheckoutTime > {0}", dtpDtlFrom.Value.ToShortDateString() });
            }
            if (dtpDtlTo.Checked)
            {
                updgvDetail.LiWhere.Add(new string[] { "CheckoutTime < {0}", dtpDtlTo.Value.AddDays(1).ToShortDateString() });
            }
            if (tbxDtlTradCode.Text != "")
            {
                updgvDetail.LiWhere.Add(new string[] { "TradeNo LIKE '%' + {0} + '%'", tbxDtlTradCode.Text.Trim() });
            }
            if (cbProName.SelectedValue.ToString() != "0")
            {
                updgvDetail.LiWhere.Add(new string[] { "Product_ID ={0}", cbProName.SelectedValue.ToString() });
            }
            if (cbServer.SelectedValue.ToString() != "0")
            {
                updgvDetail.LiWhere.Add(new string[] { "Employee_ID = {0}", cbServer.SelectedValue.ToString() });
            }
            if (tbxOrderNoDtl.Text.Trim() != "")
            {
                updgvDetail.LiWhere.Add(new string[] { "OrderNo LIKE '%' + {0} + '%'", tbxOrderNoDtl.Text.Trim() });
            }
            updgvDetail.CurPage = 1;
            dgvDetail.DataSource = updgvDetail.GetDataTable();
            GetDtlTotalAmount();
        }

        private void btnDtlExport_Click(object sender, EventArgs e)
        {
            FormExport fe = new FormExport(updgvDetail);
            fe.ShowDialog();
        }
    }
}
<file_sep>﻿using System;
using Service.Common.Entity;
namespace Message.Model
{
	/// <summary>
	/// CardType:实体类(属性说明自动提取数据库字段的描述信息)
	/// </summary>
    [TableAttribute("CardType")]
    public partial class CardType : EntityBase<CardType>
	{
		public CardType()
		{}
		#region Model
		private int _id;
        private int _vailable;
		private string _typename;
		private decimal _discount;
		/// <summary>
		/// 
		/// </summary>
        [PrimaryKey("ID", IsAuto = true)]
		public int ID
		{
			set{ _id=value;}
			get{return _id;}
		}
		/// <summary>
		/// 
		/// </summary>
        [Property]
        public int Available
		{
            set { _vailable = value; }
            get { return _vailable; }
		}
		/// <summary>
		/// 类型名称
		/// </summary>
        [Property]
        public string TypeName
		{
			set{ _typename=value;}
			get{return _typename;}
		}
		/// <summary>
		/// 折扣
        /// </summary>
        [Property]
        public decimal Discount
		{
			set{ _discount=value;}
			get{return _discount;}
		}
		#endregion Model

	}
}

<file_sep>﻿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 Message.Model;
using Service.Common;

namespace WinApp.WinForm.Admin
{
    public partial class FormRecharge : Form
    {
        MemberCard mc = new MemberCard();
        public FormRecharge(Int32 cardId)
        {
            InitializeComponent();
            mc.FindbyPK(cardId.ToString());
        }

        private void btnDetermine_Click(object sender, EventArgs e)
        {
            if (tbxRechargeAmount.Text.Trim() != "")
            {
                if (new FormBackPassword().ShowDialog() == DialogResult.OK)
                {
                    if (MessageBox.Show("您确定要向卡号：" + mc.CardNO + " 姓名：" + mc.MemberName + " 的用户充值 " + tbxRechargeAmount.Text + " 元吗？", "充值确认", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                    {
                        mc.Balance += Convert.ToInt32(tbxRechargeAmount.Text);
                        mc.Update();
                        ConsumptionRecords cr = new ConsumptionRecords();
                        cr.CardID = mc.ID;
                        cr.RecType = 1;
                        cr.TradeNo = "-----------";
                        cr.OpeTime = DateTime.Now;
                        cr.Amount = Convert.ToInt32(tbxRechargeAmount.Text);
                        cr.Insert();
                        MessageBox.Show("充值成功！");
                        DialogResult = DialogResult.OK;
                    }
                }
            }
            else
            {
                MessageBox.Show("请填写充值金额！");
            }
        }

        private void tbxRechargeAmount_KeyPress(object sender, KeyPressEventArgs e)
        {
            ControlCommon.VerDigitalHL(sender, e);
        }
    }
}
<file_sep>﻿using System;
using Service.Common.Entity;
namespace Message.Model
{
	/// <summary>
	/// ProductSpec:实体类(属性说明自动提取数据库字段的描述信息)
	/// </summary>
    [TableAttribute("ProductSpec")]
    public partial class ProductSpec : EntityBase<ProductSpec>
	{
		public ProductSpec()
		{}
		#region Model
		private int _productspec_id;
		private string _name;
		private int _employee_id;
		private DateTime _createdate= DateTime.Now;
		private string _remark;
		/// <summary>
		/// 
		/// </summary>
        [PrimaryKey("ProductSpec_ID", IsAuto = true)]
		public int ProductSpec_ID
		{
			set{ _productspec_id=value;}
			get{return _productspec_id;}
		}
		/// <summary>
		/// 
        /// </summary>
        [Property]
		public string Name
		{
			set{ _name=value;}
			get{return _name;}
		}
		/// <summary>
		/// 
        /// </summary>
        [Property]
		public int Employee_ID
		{
			set{ _employee_id=value;}
			get{return _employee_id;}
		}
		/// <summary>
		/// 
        /// </summary>
        [Property]
		public DateTime CreateDate
		{
			set{ _createdate=value;}
			get{return _createdate;}
		}
		/// <summary>
		/// 
        /// </summary>
        [Property]
		public string Remark
		{
			set{ _remark=value;}
			get{return _remark;}
		}
		#endregion Model

	}
}

<file_sep>﻿using System;
using Service.Common.Entity;
namespace Message.Model
{
	/// <summary>
	/// Employee:实体类(属性说明自动提取数据库字段的描述信息)
	/// </summary>
    [TableAttribute("Employee")]
    public partial class Employee : EntityBase<Employee>
	{
		public Employee()
		{}
		#region Model
        private Int32 _employee_id;
		private string _username;
		private string _password;
		private int _dept_id;
		private string _name;
		private string _duty;
		private string _gender;
		private DateTime _birthdate;
		private DateTime _hiredate;
        private DateTime _lastlogin;
		private string _identitycard;
		private string _address;
		private string _phone;
		private string _email;
        private string _remark;
		/// <summary>
		/// 
		/// </summary>
        [PrimaryKey("Employee_ID", IsAuto = true)]
        public Int32 Employee_ID
		{
			set{ _employee_id=value;}
			get{return _employee_id;}
		}
		/// <summary>
		/// 
		/// </summary>
        [Property]
        public string UserName
		{
			set{ _username=value;}
			get{return _username;}
		}
		/// <summary>
		/// 
		/// </summary>
        [Property]
        public string PassWord
		{
			set{ _password=value;}
			get{return _password;}
		}
		/// <summary>
		/// 
		/// </summary>
        [Property]
        public int Dept_ID
		{
			set{ _dept_id=value;}
			get{return _dept_id;}
		}
		/// <summary>
		/// 
		/// </summary>
        [Property]
        public string Name
		{
			set{ _name=value;}
			get{return _name;}
		}
		/// <summary>
		/// 
		/// </summary>
        [Property]
        public string Duty
		{
			set{ _duty=value;}
			get{return _duty;}
		}
		/// <summary>
		/// 
		/// </summary>
        [Property]
        public string Gender
		{
			set{ _gender=value;}
			get{return _gender;}
		}
		/// <summary>
		/// 
		/// </summary>
        [Property]
        public DateTime BirthDate
		{
			set{ _birthdate=value;}
			get{return _birthdate;}
		}
		/// <summary>
		/// 
		/// </summary>
        [Property]
        public DateTime HireDate
		{
			set{ _hiredate=value;}
			get{return _hiredate;}
		}
		/// <summary>
		/// 
		/// </summary>
        [Property]
        public DateTime LastLogin
		{
            set { _lastlogin = value; }
            get { return _lastlogin; }
		}
		/// <summary>
		/// 
		/// </summary>
        [Property]
        public string IdentityCard
		{
			set{ _identitycard=value;}
			get{return _identitycard;}
		}
		/// <summary>
		/// 
		/// </summary>
        [Property]
        public string Address
		{
			set{ _address=value;}
			get{return _address;}
		}
		/// <summary>
		/// 
		/// </summary>
        [Property]
        public string Phone
		{
			set{ _phone=value;}
			get{return _phone;}
		}
		/// <summary>
		/// 
		/// </summary>
        [Property]
        public string Email
		{
			set{ _email=value;}
			get{return _email;}
		}
        /// <summary>
        /// 
        /// </summary>
        [Property]
        public string Remark
        {
            set { _remark = value; }
            get { return _remark; }
        }
		#endregion Model

	}
}

<file_sep>﻿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 System.Threading;
using Message.Model;
using Service.Common;
using WinApp.Controls;

namespace WinApp.WinForm.Report
{
    public partial class FormExport : Form
    {
        Sale SaleInfo = new Sale();
        Sale_Detail sdInfo = new Sale_Detail();
        UCPage ucpage = new UCPage();
        public FormExport(UCPage UCPage)
        {
            Control.CheckForIllegalCrossThreadCalls = false; 
            InitializeComponent();
            ee.ExportEvent += new ExcelExportEntrust(ee_ExportEvent);
            ExportSummary(UCPage);
        }
        ExcelExport ee = new ExcelExport();
        private void ExportSummary(UCPage ucPage)
        {
            ucpage = ucPage;
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                backgroundWorker1.RunWorkerAsync();
            }
            else
            {
                Close();
            }
        }

        void ee_ExportEvent(int Schedule)
        {
            backgroundWorker1.ReportProgress(Schedule);
            progressBar1.Value = Schedule;
            lbSchedule.Text = "正在导出，已完成 " + Schedule + "%。。。。。。";
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            dt = SaleInfo.GetDataSet(ucpage.DataSetSql, ucpage.LiWhere, ucpage.LiOrder);
            if (dt.Rows.Count > 65000)
            {
                MessageBox.Show("汇总统计表的行数已经超过Excel文件的容量（65536行），不能导出，请缩小统计范围！");
                return;
            }
            ds.Tables.Add(dt.Copy());

            Employee emp = new Employee();
            emp.FindbyPK(Thread.CurrentPrincipal.Identity.Name);
            string PeriodTime = "";

            List<string[]> liWhere = ucpage.LiWhere;
            for (int i = 0; i < liWhere.Count; i++)
            {
                if (liWhere[i][0] == "CheckoutTime > {0}")
                {
                    PeriodTime += Convert.ToDateTime(liWhere[i][1]).ToString("yyyy-M-d") + "～";
                }
                if (liWhere[i][0] == "CheckoutTime < {0}")
                {
                    PeriodTime += Convert.ToDateTime(liWhere[i][1]).AddDays(-1).ToString("yyyy-M-d");
                }
            }


            DataTable dtInfo = new DataTable();
            dtInfo.Columns.Add("name", typeof(string));
            ds.Tables.Add(dtInfo);

            DataRow row = ds.Tables[1].NewRow();
            row[0] = emp.Name;
            dtInfo.Rows.InsertAt(row, 0);

            DataRow row1 = ds.Tables[1].NewRow();
            row1["name"] = DateTime.Now.ToString("yyyy-M-d HH:mm:ss");
            dtInfo.Rows.InsertAt(row1, 0);

            DataRow row2 = ds.Tables[1].NewRow();
            row2["name"] = PeriodTime;
            dtInfo.Rows.InsertAt(row2, 0);

            if (ucpage.Name == "updgvSummary")
            {
                ee.Export(ds, "kqzdhz", folderBrowserDialog1.SelectedPath + "\\销售汇总表");
            }
            else
            {
                ee.Export(ds, "kqzdmx", folderBrowserDialog1.SelectedPath + "\\销售明细表");
            }
            
            System.Diagnostics.Process.Start("Explorer.exe", folderBrowserDialog1.SelectedPath);
            DialogResult = DialogResult.OK;
        }
    }
}
<file_sep>﻿using System;
using Service.Common.Entity;
namespace Message.Model
{
	/// <summary>
	/// Sale_Detail:实体类(属性说明自动提取数据库字段的描述信息)
	/// </summary>
    [TableAttribute("Sale_Detail")]
    public partial class Sale_Detail : EntityBase<Sale_Detail>
	{
		public Sale_Detail()
		{}
		#region Model
        private int _sale_detail_ID_id;
		private int _product_id;
		private int _saleorder_id;
		private decimal _quantity;
		private decimal _price;
        private decimal _discount;
        private int _employee_id;
        private DateTime sale_Dtl_Time;

        
		/// <summary>
		/// 
		/// </summary>
        [PrimaryKey("Sale_Detail_ID", IsAuto = true)]
        public int Sale_Detail_ID
		{
            set { _sale_detail_ID_id = value; }
            get { return _sale_detail_ID_id; }
		}
		/// <summary>
		/// 
        /// </summary>
        [Property]
		public int Product_ID
		{
			set{ _product_id=value;}
			get{return _product_id;}
		}
		/// <summary>
		/// 
        /// </summary>
        [Property]
		public int SaleOrder_ID
		{
			set{ _saleorder_id=value;}
			get{return _saleorder_id;}
		}
		/// <summary>
		/// 
        /// </summary>
        [Property]
		public decimal Quantity
		{
			set{ _quantity=value;}
			get{return _quantity;}
		}
		/// <summary>
		/// 
        /// </summary>
        [Property]
		public decimal Price
		{
			set{ _price=value;}
			get{return _price;}
		}
		/// <summary>
		/// 
        /// </summary>
        [Property]
        public decimal Discount
		{
			set{ _discount=value;}
			get{return _discount;}
		}
        /// <summary>
        /// 
        /// </summary>
        [Property]
        public int Employee_ID
        {
            set { _employee_id = value; }
            get { return _employee_id; }
        }
        /// <summary>
        /// 
        /// </summary>
        [Property]
        public DateTime Sale_Dtl_Time
        {
            get { return sale_Dtl_Time; }
            set { sale_Dtl_Time = value; }
        }
		#endregion Model

	}

    public class SaleDtlInfo
    {
        public SaleDtlInfo()
        {}
        Int32 proID;
        string proCode;
        string proName;
        decimal paidIn;
        decimal price;
        decimal quanity;
        decimal discount;
        decimal total;
        Int32 serverID;
        string server;
        DateTime sale_Dtl_Time;

        /// <summary>
        /// 商品ID
        /// </summary>
        public Int32 ProID
        {
            get { return proID; }
            set { proID = value; }
        }
        /// <summary>
        /// 商品编号
        /// </summary>
        public string ProCode
        {
            get { return proCode; }
            set { proCode = value; }
        }
        /// <summary>
        /// 商品名称
        /// </summary>
        public string ProName
        {
            get { return proName; }
            set { proName = value; }
        }
        /// <summary>
        /// 实际单价
        /// </summary>
        public decimal PaidIn
        {
            get { return paidIn; }
            set { paidIn = value; }
        }
        /// <summary>
        /// 商品原价
        /// </summary>
        public decimal Price
        {
            get { return price; }
            set { price = value; }
        }
        /// <summary>
        /// 数量
        /// </summary>
        public decimal Quanity
        {
            get { return quanity; }
            set { quanity = value; }
        }
        /// <summary>
        /// 折扣幅度
        /// </summary>
        public decimal Discount
        {
            get { return discount; }
            set { discount = value; }
        }
        /// <summary>
        /// 共计金额
        /// </summary>
        public decimal Total
        {
            get { return total; }
            set { total = value; }
        }
        /// <summary>
        /// 服务人员ID
        /// </summary>
        public Int32 ServerID
        {
            get { return serverID; }
            set { serverID = value; }
        }
        /// <summary>
        /// 服务人员姓名
        /// </summary>
        public string Server
        {
            get { return server; }
            set { server = value; }
        }
        /// <summary>
        /// 添加时间
        /// </summary>
        public DateTime Sale_Dtl_Time
        {
            get { return sale_Dtl_Time; }
            set { sale_Dtl_Time = value; }
        }
    }
}

<file_sep>﻿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 Message.Model;
using Service.Common;

namespace WinApp.WinForm
{
    public partial class FormMemCard : Form
    {
        MemberCard mc = new MemberCard();
        CardType ct = new CardType();
        string cardNo;
        decimal paymentCard;

        public decimal PaymentCard
        {
            get { return paymentCard; }
            set { paymentCard = value; }
        }
        public string CardNo
        {
            get { return cardNo; }
            set { cardNo = value; }
        }
        public FormMemCard(decimal TotalAmount)
        {
            InitializeComponent();
            lbAmount.Text = TotalAmount.ToString("f2");
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            if (tbxCardNo.Text.Trim()!="")
            {
                List<string[]> where = new List<string[]>();
                where.Add(new string[] { "CardNO = {0}", tbxCardNo.Text.Trim() });
                DataTable dt = mc.GetDataSet("SELECT TOP 1 ID FROM MemberCard", where);
                if (dt.Rows.Count > 0)
                {
                    string CardID = dt.Rows[0][0].ToString();
                    mc.FindbyPK(CardID);
                    ct.FindbyPK(mc.CardType.ToString());
                    this.lbCardType.Text = ct.TypeName;
                    lbCardNo.Text = mc.CardNO;
                    lbMemberName.Text = mc.MemberName;
                    lbUserTel.Text = mc.UserTel;
                    lbHandleTime.Text = mc.HandleTime.ToString("yyyy-MM-dd HH:mm:ss");
                    lbLastUse.Text = mc.LastUse.ToString("yyyy-MM-dd HH:mm:ss");
                    lbBalance.Text = mc.Balance.ToString("f2");
                    if (tbxConsumption.Text == "")
                    {
                        if (Convert.ToDecimal(lbBalance.Text) >= Convert.ToDecimal(lbAmount.Text))
                        {
                            tbxConsumption.Text = lbAmount.Text;
                        }
                        else
                        {
                            tbxConsumption.Text = lbBalance.Text;
                        }
                    }
                    lbCannotFind.Visible = false;
                }
                else
                {
                    lbMemberName.Text = "";
                    lbCardType.Text = "";
                    lbMemberName.Text = "";
                    lbUserTel.Text = "";
                    lbHandleTime.Text = "";
                    lbLastUse.Text = "";
                    lbBalance.Text = "";
                    lbCannotFind.Visible = true;
                    tbxConsumption.Text = "";
                    lbCardNo.Text = "";
                }
            }
        }


        private void tbxlbConsumption_KeyPress(object sender, KeyPressEventArgs e)
        {
            ControlCommon.VerDecimal(sender, e);
        }

        private void btnDetermine_Click(object sender, EventArgs e)
        {
            if (lbCardNo.Text!="")
            {
                if (Convert.ToDecimal(tbxConsumption.Text) >= 0 && Convert.ToDecimal(tbxConsumption.Text) <= Convert.ToDecimal(lbBalance.Text) && Convert.ToDecimal(tbxConsumption.Text) <= Convert.ToDecimal(lbAmount.Text))
                {
                    paymentCard = Convert.ToDecimal(tbxConsumption.Text);
                    cardNo = lbCardNo.Text;
                    this.DialogResult = DialogResult.OK;
                }
                else
                {
                    MessageBox.Show("消费金额输入有误！");
                }
            }
        }
    }
}
<file_sep>﻿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 Message.Model;
using Service.Common;

namespace WinApp.WinForm.Admin
{
    public partial class FormEmpDtl : Form
    {
        Employee emp = new Employee();
        public FormEmpDtl(Int32 Employee_ID)
        {
            InitializeComponent();
            if (Employee_ID!=0)
            {
                LoadInfo(Employee_ID);
            }
        }
        private void LoadInfo(Int32 EmpID)
        {
            emp.FindbyPK(EmpID.ToString());
            tbxUserName.Text = emp.UserName;
            tbxName.Text = emp.Name;
            tbxDuty.Text = emp.Duty;
            tbxIdentityCard.Text = emp.IdentityCard;
            tbxAddress.Text = emp.Address;
            tbxPhone.Text = emp.Phone;
            tbxEmail.Text = emp.Email;
            tbxRemark.Text = emp.Remark;
            dtpBirthDate.Value = emp.BirthDate;
            if (emp.Gender == "男")
            {
                rbMale.Checked = true;
            }
            else
            {
                rbFemale.Checked = true;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            SaveUserInfo();
        }
        private void SaveUserInfo()
        {
            if (tbxUserName.Text.Trim()=="")
            {
                MessageBox.Show("请填写登录名！");
                return;
            }
            if (tbxName.Text.Trim() == "")
            {
                MessageBox.Show("请填写姓名！");
                return;
            }

            List<string[]> liWhere = new List<string[]>();
            liWhere.Add(new string[] { "UserName = {0}", tbxUserName.Text });
            if (emp.GetDataSetCount("SELECT ID FROM Employee", liWhere) > 0)
            {
                MessageBox.Show("该登录名已经存在！");
                return;
            }
            emp.UserName = tbxUserName.Text;
            emp.Name = tbxName.Text;
            emp.Duty = tbxDuty.Text;
            emp.IdentityCard = tbxIdentityCard.Text;
            emp.Address = tbxAddress.Text;
            emp.Phone = tbxPhone.Text;
            emp.Email = tbxEmail.Text;
            emp.Remark = tbxRemark.Text;
            emp.BirthDate = dtpBirthDate.Value;
            if (rbMale.Checked)
            {
                emp.Gender = "男";
            }
            else
            {
                emp.Gender = "女";
            }
            if (emp.Employee_ID == 0)
            {
                emp.PassWord = <PASSWORD>Encrypt.EncryptText("<PASSWORD>");
                emp.Dept_ID = 1;
                emp.LastLogin = DateTime.Now;
                emp.HireDate = DateTime.Now;
                emp.Insert();
            }
            else
            {
                emp.Update();
            }
            DialogResult = DialogResult.OK;
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}
<file_sep>﻿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 Message.Model;
using System.Threading;
using Service.Common.Log;
using Service.Common;
using Service.Common.Data;

namespace WinApp.WinForm
{
    public partial class FormSale : Form
    {
        Form ParentForm1;
        Sale SaleInfo = new Sale();
        Sale_Detail SaleDtl = new Sale_Detail();
        bool IsChanged = false;
        Int32 FrmSaleID;
        public FormSale(Form parentForm, Int32 SaleID)
        {
            InitializeComponent();
            FrmSaleID = SaleID;
            dataGridView1.AutoGenerateColumns = false;
            ParentForm1 = parentForm;
            LoadInfo(SaleID);
        }

        private void FormSale_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (IsChanged)
            {
                DialogResult confirm = MessageBox.Show("是否保存对此单信息的更改？", "表单内容已更改", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation);
                if (confirm == DialogResult.Yes)
                {
                    if (CustIsExists())
                    {
                        e.Cancel = true;
                        return;
                    }
                    SaveInfo();
                    ParentForm1.Show();
                }
                else if (confirm == DialogResult.No)
                {
                    ParentForm1.Show();
                }
                else
                {
                    e.Cancel = true;
                }
            }
            else
            {
                ParentForm1.Show();
            }
        }

        private void btnReturn_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            FormSelect fs1 = new FormSelect();
            if (fs1.ShowDialog() == DialogResult.OK)
            {
                DataTable dt = (DataTable)(dataGridView1.DataSource);
                DataRow dr = dt.NewRow();
                dr["Product_ID"] = fs1.SaleInfo.ProID;
                dr["Code"] = fs1.SaleInfo.ProCode;
                dr["ProductName"] = fs1.SaleInfo.ProName;
                dr["Price"] = fs1.SaleInfo.Price;
                dr["Quantity"] = fs1.SaleInfo.Quanity;
                dr["Discount"] = fs1.SaleInfo.Discount;
                dr["PaidIn1"] = fs1.SaleInfo.PaidIn;
                dr["PaidInAmount"] = fs1.SaleInfo.PaidIn;
                dr["Name"] = fs1.SaleInfo.Server;
                dr["Employee_ID"] = fs1.SaleInfo.ServerID;
                dr["Sale_Dtl_Time"] = fs1.SaleInfo.Sale_Dtl_Time;
                dt.Rows.Add(dr);//显示的内容
                IsChanged = true;
            }
        }

        private void LoadInfo(Int32 SaleID)
        {

            //DataGridViewComboBoxColumn dgvComboBoxColumn = dataGridView1.Columns["Discount"] as DataGridViewComboBoxColumn;
            DataGridViewComboBoxColumn dgvComboBoxColumn = (DataGridViewComboBoxColumn)dataGridView1.Columns["Discount"];
            dgvComboBoxColumn.DataPropertyName = "Discount";
            dgvComboBoxColumn.DataSource = ExecuteSql.ExeComSqlForDataSet("SELECT DiscountRate,DisName FROM Discount WHERE Available = 1").Tables[0];
            dgvComboBoxColumn.DisplayMember = "DisName";
            dgvComboBoxColumn.ValueMember = "DiscountRate";

            string strSql = "SELECT Sale_Detail_ID,Product_ID,Code,ProductName,Price,Quantity,Discount,0.0 AS PaidIn1,0.0 AS PaidInAmount,Total,Name,Employee_ID,Sale_Dtl_Time FROM v_SaleDetailList";
            if (SaleID != 0)
            {
                this.Text = SaleID.ToString();
                SaleInfo.FindbyPK(SaleID.ToString());
                lbTradeNo.Text = SaleInfo.TradeNo;
                tbxOrderNo.Text = SaleInfo.OrderNo;
                tbxCustomer.Text = SaleInfo.Customer.ToString();
                tbxCustomer.ReadOnly = true;
                tbxStoreHouse_ID.Text = SaleInfo.StoreHouse_ID.ToString();
                lbSaleDate.Text = SaleInfo.SaleDate.ToString("yyyy-MM-dd HH:mm:ss");

                List<string[]> where = new List<string[]>();
                List<string[]> order = new List<string[]>();
                where.Add(new string[] { "SaleOrder_ID = {0}", SaleID.ToString() });
                order.Add(new string[] { "Sale_Detail_ID", "ASC" });
                DataTable dt = SaleInfo.GetDataSet(strSql, where, order);
                dataGridView1.DataSource = dt;
            }
            else
            {
                List<string[]> where = new List<string[]>();
                where.Add(new string[] { "SaleOrder_ID = {0}", SaleID.ToString() });
                DataTable dt = SaleInfo.GetDataSet(strSql, where);
                dataGridView1.DataSource = dt;
            }
            ((DataTable)dataGridView1.DataSource).Columns["PaidInAmount"].Expression = "Convert(Price*Quantity*Discount, 'System.Decimal')";
            ((DataTable)dataGridView1.DataSource).Columns["PaidIn1"].Expression = "Convert(Price*Discount, 'System.Decimal')";
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (CustIsExists())
            {
                return;
            }
            SaveInfo();
            Close();
            ParentForm1.Show();

        }

        private void SaveInfo()
        {
            if (FrmSaleID == 0)
            {
                SaleInfo.SaleDate = DateTime.Now;
                SaleInfo.TradeNo = SaleInfo.getTradCode();
                SaleInfo.OrderNo = tbxOrderNo.Text.Trim();
                SaleInfo.Dept_ID = 1;
                SaleInfo.Employee_ID = Convert.ToInt32(Thread.CurrentPrincipal.Identity.Name);
                SaleInfo.StoreHouse_ID = Convert.ToInt32(tbxStoreHouse_ID.Text);
                SaleInfo.Address = "沈阳市皇姑区歧山中路49号";
                SaleInfo.Account = "0000";
                SaleInfo.GatheringWay = "";
                SaleInfo.Customer = Convert.ToInt32(tbxCustomer.Text);
                SaleInfo.TotalAmount = Convert.ToDecimal(lbTotal.Text);
                SaleInfo.CheckoutTime = DateTime.Now;
                ReturnMessage rm = SaleInfo.Insert();
                lbTradeNo.Text = SaleInfo.TradeNo;
                if (rm.IsSucessed)
                {
                    FrmSaleID = Convert.ToInt32(rm.Message);
                    SaleInfo.FindbyPK(FrmSaleID.ToString());
                }
                else
                {
                    MessageBox.Show("保存失败，" + rm.Message);
                    return;
                }
            }
            else
            {
                SaleInfo.StoreHouse_ID = Convert.ToInt32(tbxStoreHouse_ID.Text);
                SaleInfo.Customer = Convert.ToInt32(tbxCustomer.Text);
                SaleInfo.TotalAmount = Convert.ToDecimal(lbTotal.Text);
                SaleInfo.Update();
            }
            DataTable gvTable = (DataTable)dataGridView1.DataSource;
            for (int i = 0; i < gvTable.Rows.Count; i++)
            {
                SaleDtl = new Sale_Detail();
                SaleDtl.Product_ID = Convert.ToInt32(gvTable.Rows[i]["Product_ID"]);
                SaleDtl.SaleOrder_ID = FrmSaleID;
                SaleDtl.Quantity = Convert.ToDecimal(gvTable.Rows[i]["Quantity"]);
                SaleDtl.Price = Convert.ToDecimal(gvTable.Rows[i]["PaidIn1"]);
                SaleDtl.Discount = Convert.ToDecimal(gvTable.Rows[i]["Discount"]);
                SaleDtl.Employee_ID = Convert.ToInt32(gvTable.Rows[i]["Employee_ID"]);
                SaleDtl.Sale_Dtl_Time = Convert.ToDateTime(gvTable.Rows[i]["Sale_Dtl_Time"]);
                if (gvTable.Rows[i]["Sale_Detail_ID"].ToString() == "")
                {
                    SaleDtl.Insert();
                }
                else
                {
                    SaleDtl.Sale_Detail_ID = Convert.ToInt32(gvTable.Rows[i]["Sale_Detail_ID"]);
                    SaleDtl.Update();
                }
            }
            IsChanged = false;
        }

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            if (e.RowIndex >= dataGridView1.FirstDisplayedScrollingRowIndex)
            {
                using (SolidBrush b = new SolidBrush(dataGridView1.RowHeadersDefaultCellStyle.ForeColor))
                {
                    int linen = 0;
                    linen = e.RowIndex + 1;
                    string line = linen.ToString();
                    e.Graphics.DrawString(line, e.InheritedRowStyle.Font, b, e.RowBounds.Location.X, e.RowBounds.Location.Y + 5);
                    SolidBrush B = new SolidBrush(Color.Red);
                }
            }
        }

        private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            StatisticsAmount();
        }

        private void StatisticsAmount()
        {
            decimal TotalAmount = 0;
            DataTable dt = (DataTable)dataGridView1.DataSource;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                TotalAmount += Convert.ToDecimal(dt.Rows[i]["PaidInAmount"]);
            }
            lbTotal.Text = Math.Floor(Convert.ToDouble(TotalAmount) + 0.5).ToString("f2");
        }

        private void tbxCustomer_KeyPress(object sender, KeyPressEventArgs e)
        {
            ControlCommon.VerDigital(e);
        }

        private void tbxStoreHouse_ID_KeyPress(object sender, KeyPressEventArgs e)
        {
            ControlCommon.VerDigital(e);
        }


        private void tbxCustomer_KeyUp(object sender, KeyEventArgs e)
        {
            IsChanged = true;
        }

        private void tbxStoreHouse_ID_KeyUp(object sender, KeyEventArgs e)
        {
            IsChanged = true;
        }

        private void btnCashier_Click(object sender, EventArgs e)
        {
            if (CustIsExists())
            {
                return;
            }
            SaveInfo();
            FormCashier frmCashier = new FormCashier(FrmSaleID);
            ReturnMessage rm;
            if (frmCashier.ShowDialog() == DialogResult.OK)
            {
                SaleInfo.TotalAmount = frmCashier.PaymentInfo.TotalAmount;
                SaleInfo.Cash = frmCashier.PaymentInfo.Cash;
                SaleInfo.UnionPay = frmCashier.PaymentInfo.UnionPay;
                SaleInfo.OtherPayment = frmCashier.PaymentInfo.OtherPayment;
                SaleInfo.Account = frmCashier.PaymentInfo.Account;
                SaleInfo.MemCard = frmCashier.PaymentInfo.MemCard;
                SaleInfo.CheckoutTime = DateTime.Now;
                SaleInfo.State = 0;
                rm = SaleInfo.Update();
                if (rm.IsSucessed)
                {
                    if (frmCashier.PaymentInfo.MemCard >= 0 && frmCashier.PaymentInfo.Account != "0000")
                    {
                        rm = MemCardOper.MemCardHandle(frmCashier.PaymentInfo.Account, frmCashier.PaymentInfo.MemCard, SaleInfo.TradeNo);
                        if (!rm.IsSucessed)
                        {
                            MessageBox.Show(rm.Message);
                            SaleInfo.State = 1;
                            SaleInfo.Update();//会员卡操作失败，回滚
                            return;
                        }
                    }
                }
                else
                {
                    MessageBox.Show("结帐失败！" + rm.Message);
                    return;
                }
                string msg = "";
                if (frmCashier.PaymentInfo.Cash > 0)
                {
                    msg += "现金：" + frmCashier.PaymentInfo.Cash + "元\r";
                }
                if (frmCashier.PaymentInfo.UnionPay > 0)
                {
                    msg += "银联卡支付：" + frmCashier.PaymentInfo.UnionPay + "元\r";
                }
                if (frmCashier.PaymentInfo.MemCard > 0)
                {
                    msg += "会员卡支付：" + frmCashier.PaymentInfo.MemCard + "元\r";
                }
                if (frmCashier.PaymentInfo.OtherPayment > 0)
                {
                    msg += "其他方式支付：" + frmCashier.PaymentInfo.OtherPayment + "元\r";
                }
                if (msg != "")
                {
                    msg = "，其中\r" + msg;
                }
                /************************************************************************************/
                //打印代码放这
                PrintInfo();
                /*************************************************************************************/
                MessageBox.Show("结帐成功！\r 共消费" + frmCashier.PaymentInfo.TotalAmount + "元" + msg);
                Close();
                ParentForm1.Show();

            }
        }

        private void btnMergeBill_Click(object sender, EventArgs e)
        {
            if (CustIsExists())
            {
                return;
            }
            SaveInfo();
            FormMergeBill fmb = new FormMergeBill(FrmSaleID);
            if (fmb.ShowDialog() == DialogResult.OK)
            {
                MessageBox.Show("合并成功！");
                LoadInfo(FrmSaleID);
                StatisticsAmount();
            }
        }


        private bool CustIsExists()
        {
            if (tbxCustomer.Text.Trim() == "")
            {
                MessageBox.Show("请填写客户号！");
                tbxCustomer.Focus();
                return true;
            }
            if (tbxStoreHouse_ID.Text.Trim() == "")
            {
                MessageBox.Show("请填写房间号！");
                tbxStoreHouse_ID.Focus();
                return true;
            }
            List<string[]> liWhere = new List<string[]>();
            liWhere.Add(new string[] { "Customer = {0}", tbxCustomer.Text.Trim() });
            liWhere.Add(new string[] { "State = {0}", "1" });
            liWhere.Add(new string[] { "Sale_ID <> {0}", FrmSaleID.ToString() });
            Int32 CusCount = SaleInfo.GetDataSetCount("SELECT Sale_ID FROM Sale", liWhere);
            DataTable dt = SaleInfo.GetDataSet("SELECT Sale_ID FROM Sale", liWhere);
            if (CusCount > 0)
            {
                MessageBox.Show("该顾客号码当前还未结帐！");
                return true;
            }
            else
            {
                return false;
            }
        }


        private void PrintInfo()
        {
            DataSet ds = new DataSet();
            ds.Tables.Add(((DataTable)dataGridView1.DataSource).Copy());
            PrintCommon pc = new PrintCommon();
            pc.PrintDataSet(ds, SaleInfo);
        }

        private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (this.dataGridView1.CurrentCell.OwningColumn.Name == "Discount")
            {
                ((ComboBox)e.Control).SelectionChangeCommitted += new EventHandler(FormSale_SelectedIndexChanged);
            }
        }

        void FormSale_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataTable dt = dataGridView1.DataSource as DataTable;
            dt.Rows[dataGridView1.CurrentCell.RowIndex]["Discount"] = ((ComboBox)sender).SelectedValue;
            IsChanged = true;
        }
    }
}
<file_sep>﻿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 Message.Model;
using System.Threading;
using Service.Common;
using Service.Common.IO;

namespace WinApp.WinForm.Admin
{
    public partial class FormProdDtl : Form
    {
        Product pro = new Product();
        public FormProdDtl(Int32 ProID)
        {
            InitializeComponent();
            tbxName.Focus();
            if (ProID != 0)
            {
                LoadInfo(ProID);
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (tbxName.Text.Trim() == "")
            {
                MessageBox.Show("请填写名称！");
                return;
            }
            if (tbxPrice.Text.Trim() == "")
            {
                MessageBox.Show("请填写价格！");
                return;
            }
            if (tbxCommission.Text.Trim() == "")
            {
                MessageBox.Show("请填写提成！");
                return;
            }
            pro.Code = tbxCode.Text;
            pro.Name = tbxName.Text;
            PinyinCommon pyc = new PinyinCommon();
            pro.spell = pyc.GetQuanPing(tbxName.Text.Trim());
            pro.s_spell = pyc.GetPYString(tbxName.Text.Trim());
            pro.shortname = tbxName.Text;
            pro.Price = Convert.ToDecimal(tbxPrice.Text);
            pro.Offering_Price = Convert.ToDecimal(tbxPrice.Text);
            pro.Commission = Convert.ToDecimal(tbxCommission.Text);
            pro.Remark = tbxRemark.Text;
            if (pro.Product_ID == 0)
            {
                List<string[]> LiWhere = new List<string[]>();
                LiWhere.Add(new string[] { "Name = {0}", tbxName.Text });
                DataTable dt = pro.GetDataSet("SELECT Product_ID FROM Product", LiWhere);
                if (dt.Rows.Count > 0)
                {
                    MessageBox.Show("该商品名已存在！");
                    return;
                }
                pro.ProductList_ID = 1;
                pro.ProductSpec_ID = 1;
                pro.ProductUnit_ID = 1;
                pro.Employee_ID = Convert.ToInt32(Thread.CurrentPrincipal.Identity.Name);
                pro.CreateDate = DateTime.Now;
                string newProId = pro.Insert().Message;
                pro.FindbyPK(newProId);
                pro.Code = Convert.ToInt32(newProId).ToString("000");
                pro.Update();
            }
            else
            {
                pro.Update();
            }
            MessageBox.Show("保存成功！");
            DialogResult = DialogResult.OK;
        }

        private void LoadInfo(Int32 proID)
        {
            pro.FindbyPK(proID.ToString());
            tbxCode.Text = pro.Code;
            tbxName.Text = pro.Name;
            tbxPrice.Text = pro.Price.ToString("f2");
            tbxCommission.Text = pro.Commission.ToString("f2");
            tbxCreateDate.Text = pro.CreateDate.ToString("yyyy-MM-dd HH:mm:ss");
            Employee emp = new Employee();
            emp.FindbyPK(pro.Employee_ID.ToString());
            tbxEmployee_ID.Text = emp.Name;
            tbxRemark.Text = pro.Remark;
            tbxCreateDate.ReadOnly = true;
            tbxEmployee_ID.ReadOnly = true;
        }

        private void tbxPrice_KeyPress(object sender, KeyPressEventArgs e)
        {
            ControlCommon.VerDecimal(sender, e);
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void tbxCommission_KeyPress(object sender, KeyPressEventArgs e)
        {
            ControlCommon.VerDecimal(sender, e);
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;

namespace Service.Common.IO
{
    public class ExcelOperate
    {
        public static string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES;IMEX={1}';";
        /// <summary>
        /// 获取Excel中的表名
        /// </summary>
        /// <param name="stPath"></param>
        /// <returns></returns>
        public static String[] GetExcelSheetNames(string stPath)
        {
            OleDbConnection objConn = null;
            System.Data.DataTable dt = null;

            try
            {
                objConn = new OleDbConnection(string.Format(connString, stPath, "1"));
                objConn.Open();
                dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                if (dt == null)
                {
                    return null;
                }
                for (int n = 0; n < dt.Rows.Count; n++)
                {
                    string[] strTableName = dt.Rows[n]["TABLE_NAME"].ToString().Split('$');
                    if (strTableName.Length < 3 && strTableName[1].ToString() == "")
                    {

                    }
                    else
                    {
                        dt.Rows.RemoveAt(n);
                    }
                }

                int m = dt.Rows.Count;
                String[] excelSheets = new String[dt.Rows.Count];
                int i = 0;

                foreach (DataRow row in dt.Rows)
                {
                    excelSheets[i] = row["TABLE_NAME"].ToString();
                    i++;
                }

                return excelSheets;
            }
            catch (Exception ex)
            {
                return null;
            }
            finally
            {
                if (objConn != null)
                {
                    objConn.Close();
                    objConn.Dispose();
                }
                if (dt != null)
                {
                    dt.Dispose();
                }
            }
        }


        /// <summary>
        /// 获取源数据标题
        /// </summary>
        /// <param name="Spath">源文件路径</param>
        /// <param name="sheetName">Sheet页名称</param>
        /// <returns></returns>
        public static DataTable GetTitle(string Spath, string sheetName)
        {
            DataTable dtData = new DataTable();
            OleDbDataReader datareader = null;
            OleDbConnection Conn = null;
            try
            {
                dtData.Columns.Add("CNC");
                dtData.Columns.Add("CNE");
                dtData.Columns.Add("CK");
                dtData.Columns.Add("CJ");
                Conn = new OleDbConnection(string.Format(connString, Spath, "0"));
                Conn.Open();
                string stSQL = "select * from [" + sheetName + "$]";
                OleDbCommand dbCommand = new OleDbCommand(stSQL, Conn);
                datareader = dbCommand.ExecuteReader();
                bool IsChinese = false;
                if (datareader.FieldCount != 0)
                {
                    IsChinese = FileOperate.IsChineseChar(datareader.GetName(0));
                }
                else
                {
                    return null;
                }
                List<string> myAL = new List<string>();
                int j = 0;
                for (int i = 0; i < datareader.FieldCount; i++)
                {
                    string itemEn = StrToPinyin.GetChineseSpell(datareader.GetName(i)).ToString();
                    if (myAL.Count != 0)
                    {
                        if (myAL.Contains(itemEn) == false)
                        {
                            myAL.Add(itemEn);
                        }
                        else
                        {
                            itemEn = itemEn + j.ToString();
                            j++;
                        }
                    }
                    else
                    {
                        myAL.Add(itemEn);
                    }
                    DataRow dr = dtData.NewRow();
                    if (FileOperate.IsChineseChar(datareader.GetName(i)))
                    {
                        dr["CNC"] = datareader.GetName(i);
                        dr["CNE"] = itemEn;
                    }
                    else
                    {
                        dr["CNC"] = datareader.GetName(i);
                        dr["CNE"] = datareader.GetName(i);
                    }
                    dtData.Rows.Add(dr);
                }
            }
            catch (Exception ex)
            {
                return null;
            }
            finally
            {
                Conn.Close();
                datareader.Dispose();
            }
            return dtData;
        }
    }
}
<file_sep>﻿using System;
using Service.Common.Entity;
namespace Message.Model
{
	/// <summary>
	/// Discount:实体类(属性说明自动提取数据库字段的描述信息)
	/// </summary>
    [TableAttribute("Discount")]
    public partial class Discount : EntityBase<Discount>
	{
		public Discount()
		{}
		#region Model
		private int _id;
		private decimal _discountrate;
		private string _disname;
		private bool _available;
		private string _remark;
		/// <summary>
		/// 
		/// </summary>
        [PrimaryKey("ID", IsAuto = true)]
		public int ID
		{
			set{ _id=value;}
			get{return _id;}
		}
		/// <summary>
		/// 
        /// </summary>
        [Property]
        public decimal DiscountRate
		{
			set{ _discountrate=value;}
			get{return _discountrate;}
		}
		/// <summary>
		/// 
        /// </summary>
        [Property]
		public string DisName
		{
			set{ _disname=value;}
			get{return _disname;}
		}
		/// <summary>
		/// 
        /// </summary>
        [Property]
		public bool Available
		{
			set{ _available=value;}
			get{return _available;}
		}
		/// <summary>
		/// 
        /// </summary>
        [Property]
		public string Remark
		{
			set{ _remark=value;}
			get{return _remark;}
		}
		#endregion Model

	}
}

<file_sep>﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using Service.Common.Log;

namespace Service.Common.IO
{
    public class XMLOperator
    {
        #region 变量
        bool bValid = false;
        string stErrMessage = string.Empty;
        private long lXmlCount = 0;

        /// <summary>
        /// 文件路径
        /// </summary>
        private string stDataFile = null;

        /// <summary>
        /// 数据集
        /// </summary>
        private DataSet dsDataSet = null;

        /// <summary>
        /// 字符过滤数组 比如 "id='1' and userName='trace'" 
        /// </summary>
        private string stFilter = null;

        /// <summary>
        /// 排序的字段 比如 "id desc,userName"
        /// </summary>
        private string stSort = null;

        /// <summary>
        /// 数据集合中的字段名集合
        /// </summary>
        private string[] stFields = null;

        /// <summary>
        /// 数据集合中的数据数组
        /// </summary>
        private string[] stData = null;

        #endregion

        #region 属性
        /// <summary>
        /// 数据文件路径
        /// </summary>
        public string DataFile
        {
            set { this.stDataFile = value; }
            get { return this.stDataFile; }
        }
        /// <summary>
        /// 字符过滤数组
        /// </summary>
        public string FilterString
        {
            set { this.stFilter = value; }
        }
        /// <summary>
        /// 排序的字段
        /// </summary>
        public string SortString
        {
            set { this.stSort = value; }
        }
        /// <summary>
        /// 数据集合中的字段名
        /// </summary>
        public string[] FieldsString
        {
            set { this.stFields = value; }
        }
        /// <summary>
        /// 数据集合中的数据数组
        /// </summary>
        public string[] DataString
        {
            set { this.stData = value; }
        }
        /// <summary>
        /// 数据集合，可以放在缓存供调用
        /// </summary>
        public DataSet DataSetData
        {
            set { this.dsDataSet = value; }
            get { return this.dsDataSet; }
        }
        #endregion

        #region 构造函数

        public XMLOperator()
        {
            //
            // TODO: 提供将XML当作数据库处理的一些方法
            //
        }

        #endregion

        #region 事件

        #endregion

        #region 方法


        /// <summary>
        /// 取得XML文件的内容并填入DataSet
        /// </summary>
        public void Open()
        {
            this.dsDataSet = new DataSet();
            FileStream fin;
            fin = new FileStream(this.DataFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            this.dsDataSet.ReadXml(fin);
            fin.Close();
        }

        /// <summary>
        /// 将操作结果写入XML
        /// </summary>
        public void Save()
        {
            this.dsDataSet.WriteXml(this.DataFile);
            this.Clear();
        }

        /// <summary>
        /// 取得特定的数据视图
        /// 一般在数据绑定的时候，我们可以很方便的生成供绑定的视图
        /// </summary>
        /// <returns>数据视图</returns>
        public DataView SelectView()
        {
            if (this.dsDataSet == null) this.Open();

            DataView myDv = new DataView(this.dsDataSet.Tables[0]);

            if (stFilter != null) myDv.RowFilter = this.stFilter;

            myDv.Sort = this.stSort;

            return myDv;
        }

        /// <summary>
        /// 取得特定的行
        /// 使用行的方式是因为有些时候，我们仅仅只需要某一行或多行记录
        /// 比如我们判断登陆的时候，只是需要某个ID的所在行，然后匹配它的密码项
        /// </summary>
        /// <returns>各行数据</returns>
        public DataRow[] SelectRows()
        {
            if (this.dsDataSet == null) this.Open();
            DataRow[] myRows = dsDataSet.Tables[0].Select(this.stFilter);
            return myRows;
        }

        /// <summary>
        /// 往XML当中插入一条数据
        /// </summary>
        /// <returns>操作是否成功</returns>
        public bool InsertData()
        {
            if (this.dsDataSet == null) this.Open();
            DataRow newRow = dsDataSet.Tables[0].NewRow();

            for (int i = 0; i < this.stFields.Length; i++)
            {
                newRow[this.stFields[i]] = this.stData[i];
            }

            dsDataSet.Tables[0].Rows.Add(newRow);
            this.Save();
            return true;
        }

        /// <summary>
        /// 更新数据,这个时候要确保strFields 与 strData 两个数组的维数一致
        /// </summary>
        /// <returns>是否更新成功</returns>
        public bool UpdateData()
        {
            if (this.dsDataSet == null) this.Open();
            DataRow[] editRow = dsDataSet.Tables[0].Select(this.stFilter);

            for (int j = 0; j < editRow.Length; j++)
            {
                for (int i = 0; i < this.stFields.Length; i++)
                {
                    editRow[j][this.stFields[i]] = this.stData[i];
                }
            }
            this.Save();
            return true;
        }

        /// <summary>
        /// 删除数据
        /// </summary>
        /// <returns>是否删除成功</returns>
        public bool DeleteData()
        {
            if (this.dsDataSet == null) this.Open();

            DataRow[] editRow = dsDataSet.Tables[0].Select(this.stFilter);
            for (int i = 0; i < editRow.Length; i++)
            {
                editRow[i].Delete();
            }
            this.Save();
            return true;
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Clear()
        {
            if (this.dsDataSet != null)
            {
                this.dsDataSet.Dispose();
            }
        }
        /// <summary>
        /// 获取源数据标题
        /// </summary>
        /// <param name="Spath">源文件路径</param>
        /// <returns></returns>
        public static DataTable GetTitle(string Spath)
        {
            DataTable dtData = new DataTable();
            StreamReader sr = null;
            StringReader stringReader = null;
            try
            {
                dtData.Columns.Add("CNC");
                dtData.Columns.Add("CNE");
                dtData.Columns.Add("CK");
                dtData.Columns.Add("CJ");
                FileStream fs = new FileStream(Spath, FileMode.Open);
                Encoding Code = FileOperate.GetEncoding(fs, Encoding.Default);
                fs.Close();
                fs.Dispose();
                sr = new StreamReader(Spath, Code);
                StringBuilder sbRow = new StringBuilder();
                string NextRow = string.Empty;
                string mappingTableName = string.Empty;
                string stCell = string.Empty;
                string RootName = ConfigurationManager.AppSettings.Get("RootName");
                while ((stCell = sr.ReadLine()) != null || (NextRow.Length != 0))
                {
                    stCell = NextRow + stCell;
                    //开头
                    if (stCell.Contains("<" + RootName))
                    {
                        sbRow.Append("<" + RootName + ">");
                        stCell = stCell.Substring(stCell.IndexOf("<" + RootName));
                        NextRow = stCell.Substring(stCell.IndexOf("<" + RootName) + RootName.Length + 1);
                        NextRow = NextRow.Substring(NextRow.IndexOf(">") + 1);
                    }
                    else if (sbRow.ToString() != string.Empty)
                    {
                        if (mappingTableName != string.Empty)
                        {
                            //结尾
                            if (stCell.Contains("</" + mappingTableName + ">"))
                            {
                                sbRow.Append(stCell.Substring(0, stCell.IndexOf("</" + mappingTableName + ">") + mappingTableName.Length + 3));
                                sbRow.Append("</" + RootName + ">");
                                break;
                            }
                            else
                            {
                                NextRow = stCell;
                            }
                        }
                        if (stCell.Contains("<") && mappingTableName == string.Empty)
                        {
                            mappingTableName = stCell.Substring(stCell.IndexOf('<') + 1);
                            mappingTableName = mappingTableName.Substring(0, mappingTableName.IndexOf('>'));
                            dtData.TableName = mappingTableName;
                            sbRow.Append("<" + mappingTableName + ">");
                            NextRow = stCell.Substring(stCell.IndexOf(">") + 1);
                        }
                    }

                }
                if (sbRow.ToString() != string.Empty)
                {
                    DataSet dsTemp = new DataSet();
                    stringReader = new StringReader(sbRow.ToString());
                    dsTemp.ReadXml(stringReader);
                    bool IsChinese = false;
                    if (dsTemp.Tables[0].Columns.Count != 0)
                    {
                        IsChinese = FileOperate.IsChineseChar(dsTemp.Tables[0].Columns[0].ColumnName);
                    }
                    else
                    {
                        return dtData;
                    }
                    ArrayList myAL = new ArrayList();
                    int j = 0;
                    for (int i = 0; i < dsTemp.Tables[0].Columns.Count; i++)
                    {
                        string itemEn = StrToPinyin.GetChineseSpell(dsTemp.Tables[0].Columns[i].ColumnName).ToString();
                        if (myAL.Count != 0)
                        {
                            if (myAL.Contains(itemEn) == false)
                            {

                                myAL.Add(itemEn);
                            }
                            else
                            {
                                itemEn = itemEn + j.ToString();
                                j++;

                            }
                        }
                        else
                        {
                            myAL.Add(itemEn);
                        }
                        DataRow dr = dtData.NewRow();
                        if (FileOperate.IsChineseChar(dsTemp.Tables[0].Columns[i].ColumnName))
                        {
                            dr["CNC"] = dsTemp.Tables[0].Columns[i].ColumnName;
                            dr["CNE"] = itemEn;
                        }
                        else
                        {
                            dr["CNE"] = dsTemp.Tables[0].Columns[i].ColumnName;
                        }
                        dtData.Rows.Add(dr);
                    }
                }
            }
            catch (Exception ex)
            {
                return dtData;
            }
            finally
            {
                if (sr != null)
                {
                    sr.Close();
                    sr.Dispose();
                }
                if (stringReader != null)
                {
                    stringReader.Close();
                    stringReader.Dispose();
                }
            }
            return dtData;
        }
        /// <summary>
        /// 读取原始数据前十条
        /// </summary>
        /// <param name="Spath">源文件路径</param>
        /// <returns></returns>
        public static DataTable ReadTopTenBySource(string Spath, string mappingTableName, string[] mappingColumns, int count)
        {
            DataSet dsData = new DataSet();
            StreamReader sr = null;
            StringReader stringReader = null;
            FileStream fs = null;
            int iCount = 0;
            try
            {
                fs = new FileStream(Spath, FileMode.Open);
                Encoding Code = FileOperate.GetEncoding(fs, Encoding.Default);
                fs.Close();
                fs.Dispose();
                sr = new StreamReader(Spath, Code);
                StringBuilder sbRowAll = new StringBuilder();
                bool IsRow = false;
                string Begin = string.Empty;
                string NextRow = string.Empty;
                string stCell = string.Empty;
                string RootName = ConfigurationManager.AppSettings.Get("RootName");
                StringBuilder sbRow = new StringBuilder();
                sbRowAll.Append("<" + RootName + ">");
                while ((stCell = sr.ReadLine()) != null || (NextRow.Length != 0))
                {
                    stCell = NextRow + stCell;
                    //开头
                    if (stCell.Contains("<" + mappingTableName + ">"))
                    {
                        stCell = stCell.Substring(stCell.IndexOf("<" + mappingTableName + ">"));
                        sbRow.Append("<" + mappingTableName + ">");
                        NextRow = stCell.Substring(stCell.IndexOf("<" + mappingTableName + ">") + mappingTableName.Length + 2);
                    }
                    else
                    {
                        //结尾
                        if (stCell.Contains("</" + mappingTableName + ">"))
                        {
                            IsRow = true;
                            sbRow.Append(stCell.Substring(0, stCell.IndexOf("</" + mappingTableName + ">") + mappingTableName.Length + 3));
                            NextRow = stCell.Substring(stCell.IndexOf("</" + mappingTableName + ">") + mappingTableName.Length + 3);
                        }
                        else if (sbRow.ToString() != string.Empty)
                        {
                            sbRow.Append(stCell);
                        }
                        if (IsRow)
                        {
                            //处理一行
                            sbRowAll.Append("<" + mappingTableName + ">");
                            for (int i = 0; i < mappingColumns.Length; i++)
                            {
                                string stTemp = sbRow.ToString();
                                if (stTemp.Contains("<" + mappingColumns[i] + ">") && stTemp.Contains("</" + mappingColumns[i] + ">"))
                                {
                                    Begin = stTemp.Substring(stTemp.IndexOf("<" + mappingColumns[i] + ">") + mappingColumns[i].Length + 2);
                                    sbRowAll.Append("<" + mappingColumns[i] + ">");
                                    string stConten = Begin.Substring(0, Begin.IndexOf("</" + mappingColumns[i] + ">")).Trim();
                                    if (stConten.Contains("<![CDATA[") && stConten.Contains("]]>"))
                                    {
                                        stConten = stConten.Replace("<![CDATA[", "").Replace("]]>", "");
                                    }
                                    sbRowAll.Append("<![CDATA[");
                                    sbRowAll.Append(stConten);
                                    sbRowAll.Append("]]>");
                                    sbRowAll.Append("</" + mappingColumns[i] + ">");
                                }
                                else
                                {
                                    sbRowAll.Append("<" + mappingColumns[i] + " />");
                                }
                            }
                            sbRowAll.Append("</" + mappingTableName + ">");
                            sbRow = new StringBuilder();
                            IsRow = false;
                            iCount++;
                            if (count != -1 && iCount == count)
                            {
                                break;
                            }
                        }
                    }

                }
                sbRowAll.Append("</" + RootName + ">");
                if (sbRowAll.ToString() != string.Empty)
                {
                    stringReader = new StringReader(sbRowAll.ToString());
                    dsData.ReadXml(stringReader);
                }
            }
            catch (Exception ex)
            {
                return null;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
                if (sr != null)
                {
                    sr.Close();
                    sr.Dispose();
                }
                if (stringReader != null)
                {
                    stringReader.Close();
                    stringReader.Dispose();
                }
            }
            return dsData.Tables[0];
        }
        /// <summary>
        /// 处理数据生成带特殊字符保护的XML文件
        /// </summary>
        /// <param name="fileName">目标文件名</param>
        /// <param name="Spath">源文件路径</param>
        /// <param name="tableName">原结构表英文名</param>
        /// <param name="columns">原结构表英文列名</param>
        /// <param name="tableName">表英文名</param>
        /// <param name="columns">表英文列名</param>
        /// <param name="Tpath">目标文件路径（不以"\"结尾）</param>
        /// <returns></returns>
        public static ReturnMessage HandleToXml(string fileName, string Spath, string mappingTableName, string[] mappingColumns, string tableName, string[] columns, string Tpath)
        {
            return HandleToXml(fileName, Spath, mappingTableName, mappingColumns, tableName, columns, Tpath, -1);
        }
        /// <summary>
        /// 处理数据生成带特殊字符保护的XML文件
        /// </summary>
        /// <param name="fileName">目标文件名</param>
        /// <param name="Spath">源文件路径</param>
        /// <param name="tableName">原结构表英文名</param>
        /// <param name="columns">原结构表英文列名</param>
        /// <param name="tableName">表英文名</param>
        /// <param name="columns">表英文列名</param>
        /// <param name="Tpath">目标文件路径（不以"\"结尾）</param>
        /// <param name="count">分包条数（条数>0）</param>
        /// <returns></returns>
        public static ReturnMessage HandleToXml(string fileName, string Spath, string mappingTableName, string[] mappingColumns, string tableName, string[] columns, string Tpath, int count)
        {
            ReturnMessage rm = new ReturnMessage();
            StreamReader sr = null;
            XmlWriter xwr = null;
            int iCount = 0;//导出条数
            int IErrorCount = 0;//筛选出去的条数
            int iTableNum = 1;//表的第几部分
            string stImport = string.Empty;
            string[] EspChar = File.ReadAllLines(System.AppDomain.CurrentDomain.BaseDirectory + @"Data\EspecialChar.txt");
            try
            {
                FileStream fs = new FileStream(Spath, FileMode.Open);
                Encoding Code = FileOperate.GetEncoding(fs, Encoding.Default);
                fs.Close();
                fs.Dispose();
                sr = new StreamReader(Spath, Code);
                string RootName = "NewDataSet";
                xwr = new XmlTextWriter(Tpath + "\\" + fileName + "_" + iTableNum.ToString() + ".xml", new System.Text.UTF8Encoding());
                xwr.WriteStartDocument(true);
                xwr.WriteWhitespace("\r\n");
                xwr.WriteStartElement(RootName);
                bool IsRow = false;
                string Begin = string.Empty;
                string NextRow = string.Empty;
                string stCell = string.Empty;
                StringBuilder sbRow = new StringBuilder();
                while ((stCell = sr.ReadLine()) != null || (NextRow.Length != 0))
                {
                    stCell = NextRow + stCell;
                    //开头
                    if (stCell.Contains("<" + mappingTableName + ">"))
                    {
                        stCell = stCell.Substring(stCell.IndexOf("<" + mappingTableName + ">"));
                        sbRow.Append("<" + mappingTableName + ">");
                        NextRow = stCell.Substring(stCell.IndexOf("<" + mappingTableName + ">") + mappingTableName.Length + 2);
                    }
                    else
                    {
                        //结尾
                        if (stCell.Contains("</" + mappingTableName + ">"))
                        {
                            IsRow = true;
                            sbRow.Append(stCell.Substring(0, stCell.IndexOf("</" + mappingTableName + ">") + mappingTableName.Length + 3));
                            NextRow = stCell.Substring(stCell.IndexOf("</" + mappingTableName + ">") + mappingTableName.Length + 3);
                        }
                        else if (sbRow.ToString() != string.Empty)
                        {
                            sbRow.Append(stCell);
                        }
                        if (IsRow)
                        {
                            //获取该行的值
                            string[] stcolumn = new string[mappingColumns.Length];
                            for (int i = 0; i < stcolumn.Length; i++)
                            {
                                string stTemp = sbRow.ToString();
                                if (stTemp.Contains("<" + mappingColumns[i] + ">") && stTemp.Contains("</" + mappingColumns[i] + ">"))
                                {
                                    Begin = stTemp.Substring(stTemp.IndexOf("<" + mappingColumns[i] + ">") + mappingColumns[i].Length + 2);

                                    string stConten = Begin.Substring(0, Begin.IndexOf("</" + mappingColumns[i] + ">")).Trim();
                                    if (stConten.Contains("<![CDATA[") && stConten.Contains("]]>"))
                                    {
                                        stConten = stConten.Replace("<![CDATA[", "").Replace("]]>", "");
                                    }
                                    stcolumn[i] = stConten;
                                }
                                else
                                {
                                    stcolumn[i] = String.Empty;
                                }
                            }
                            //验证非法字符
                            bool lContainsEspChar = false;
                            //若存在特殊字符，将其保存到筛选文件里边。
                            for (int q = 0; q < stcolumn.Length; q++)
                            {
                                foreach (string stTemp in EspChar)
                                {
                                    if (stcolumn[q].ToString().Contains(stTemp))
                                    {
                                        stImport = string.Empty;
                                        for (int p = 0; p < stcolumn.Length; p++)
                                        {
                                            stImport += stcolumn[p].ToString() + "\t";
                                        }
                                        stImport += Environment.NewLine;
                                        File.AppendAllText(Tpath + @"特殊字符筛选\EspecialCharExport_" + tableName + ".txt", stImport);
                                        IErrorCount++;
                                        lContainsEspChar = true;
                                        break;
                                    }
                                }
                                if (lContainsEspChar) break;
                            }
                            if (lContainsEspChar) continue;
                            //若不包含特殊字符则进行导出

                            //判断是否写入新文件
                            if (count > 0 && (iCount + 1) / count > 0 && iCount % count == 0)
                            {
                                //结束文件
                                xwr.WriteWhitespace("\r\n");
                                xwr.WriteEndElement();
                                xwr.WriteEndDocument();
                                xwr.Flush();
                                xwr.Close();
                                //开始新文件
                                iTableNum++;
                                xwr = new XmlTextWriter(Tpath + "\\" + fileName + "_" + iTableNum.ToString() + ".xml", new System.Text.UTF8Encoding());
                                xwr.WriteStartDocument(true);
                                xwr.WriteWhitespace("\r\n");
                                xwr.WriteStartElement(RootName);
                            }
                            //处理一行
                            xwr.WriteWhitespace("\r\n\t");
                            xwr.WriteStartElement(tableName);
                            for (int i = 0; i < mappingColumns.Length; i++)
                            {
                                if (stcolumn[i] != string.Empty)
                                {
                                    xwr.WriteWhitespace("\r\n\t\t");
                                    xwr.WriteStartElement(columns[i]);
                                    xwr.WriteCData(stcolumn[i]);
                                    xwr.WriteEndElement();
                                }
                                else
                                {
                                    xwr.WriteWhitespace("\r\n\t\t");
                                    xwr.WriteElementString(columns[i], String.Empty);
                                }
                            }
                            xwr.WriteWhitespace("\r\n\t");
                            xwr.WriteFullEndElement();
                            IsRow = false;
                            sbRow = new StringBuilder();
                            //if (count != -1 && iCount == count)
                            //{
                            //    break;
                            //}
                            iCount++;
                        }
                    }

                }
                xwr.WriteWhitespace("\r\n");
                xwr.WriteEndElement();
                xwr.WriteEndDocument();
                rm.IsSucessed = true;
                rm.Message = "导出数据" + iCount.ToString() + "行";
            }
            catch (Exception ex)
            {
                rm.IsSucessed = false;
                rm.Message = ex.Message;
            }
            finally
            {
                if (xwr != null)
                {
                    xwr.Flush();
                    xwr.Close();
                }
                if (sr != null)
                {
                    sr.Close();
                    sr.Dispose();
                }
            }
            return rm;
        }
        /// <summary>
        /// 用流读取XML转换后的前10条，并套用新的结构
        /// </summary>
        /// <param name="tableName">英文表名</param>
        /// <param name="Tpath">目标文件路径</param>
        /// <param name="schemaPath">结构文件路径</param>
        /// <returns></returns>
        public static DataTable ReadTopTenByTarget(string tableName, string Spath, string schemaPath)
        {
            DataSet dsData = new DataSet();
            dsData.ReadXmlSchema(schemaPath);
            dsData.ReadXml(Spath);
            for (int j = 0; j < dsData.Tables[tableName].Columns.Count; j++)
            {
                dsData.Tables[tableName].Columns[j].ColumnName = dsData.Tables[tableName].Columns[j].Caption;
            }
            return dsData.Tables[tableName];
        }




        void XmlReaderValidationEventHandler(object sender, ValidationEventArgs e)
        {
            //搜集e.Message中的错误信息，并填充到stErrMessage中
            //将bValid设置成false
            stErrMessage = e.Message.ToString();
            this.bValid = false;
            ReturnMessage message = new ReturnMessage();
            message.Message = stErrMessage;
            message.IsSucessed = bValid;
        }
        /// <summary>
        /// 验证数据文件
        /// </summary>
        /// <param name="xmlSchemaPath">架构文件路径</param>
        /// <param name="xmlPath">数据文件路径</param>
        private  void ValidData(string xmlSchemaPath, string xmlPath)
        {
            bValid = true;
            XmlReaderSettings xrsValid = new XmlReaderSettings();
            xrsValid.CloseInput = true;
            xrsValid.IgnoreComments = true;
            xrsValid.IgnoreWhitespace = true;
            xrsValid.ValidationType = ValidationType.Schema;
            xrsValid.Schemas.Add(null, xmlSchemaPath);
            xrsValid.CheckCharacters = false;
            xrsValid.ValidationEventHandler += new System.Xml.Schema.ValidationEventHandler(XmlReaderValidationEventHandler);
            XmlReader xrdValid = XmlReader.Create(xmlPath, xrsValid);
            while (xrdValid.Read())
            {

            }
            xrdValid.Close();
            //return false;
            //构建一个XmlReaderSettings用于验证要导入的XML信息
            //设置XmlReaderSettings
            //构建XmlReader用以读取数据，附加前面设置好的XmlReaderSettings
            //循环读取XmlReader
        }



        public ReturnMessage XmlSplit(string xmlPath, string xmlSchemaPath)
        {

            int iRowCounter = 20000;
            ArrayList alsSplitXmlName = new ArrayList();
            int iCounters = 0;
            string stSplitXmlName = String.Empty;
            ReturnMessage returnMessage = new ReturnMessage(true);
            try
            {
                //验证数据文件
                ValidData(xmlSchemaPath, xmlPath);
                //拆分文件路径
                string stSystemp = xmlPath.Substring(0, xmlPath.LastIndexOf('\\')) + "\\Systemp";
                if (!Directory.Exists(stSystemp))
                {
                    Directory.CreateDirectory(stSystemp);
                }
                else
                {
                    DirectoryOperate.ClearDirectory(stSystemp);
                }
                //string stProjectName = "";
                int iks = 0;

                if (bValid)
                {
                    #region 拆分XML
                    string stCurrentTableName = String.Empty;
                    ArrayList alsSplitIndex = new ArrayList();
                    XmlTextReader xrdSplit = new XmlTextReader(xmlPath);
                    XmlTextWriter xwrSplit = null;
                    XmlWriterSettings xwsSplitValue = new XmlWriterSettings();
                    xwsSplitValue.Encoding = Encoding.UTF8;
                    while (xrdSplit.Read())
                    {
                        iks = iks + 1;
                        //aa[iks] = ((System.Xml.XmlReader)(xrdSplit)).Value;
                        //深度大于1时，直接向分隔XML里赋值
                        if (xrdSplit.Depth > 1)
                        {
                            xwrSplit.WriteNode(xrdSplit, false);

                        }
                        //深度等于1时，依条件判断处理
                        else if (object.Equals(xrdSplit.Depth, 1))
                        {
                            //当节点为起始节点，并且不是空行节点时
                            if (xrdSplit.IsStartElement() && !xrdSplit.IsEmptyElement)
                            {
                                //当缓存列表为空时，添加新的表名到缓存列表中
                                if (Object.Equals(alsSplitXmlName.Count, 0))
                                {
                                    alsSplitXmlName.Add(xrdSplit.Name.ToString());
                                }
                                //当节点与缓存列表中的最后一位相等时,计数器累加
                                if (Object.Equals((alsSplitXmlName[alsSplitXmlName.Count - 1]).ToString(), xrdSplit.Name.ToString()))
                                {
                                    iCounters++;
                                    //如果当前节点为第一个节点，生成新的Xml头
                                    if (Object.Equals(iCounters, 1))
                                    {
                                        stSplitXmlName = String.Format(stSystemp + "\\{0}.xml", Guid.NewGuid().ToString());
                                        alsSplitIndex.Add(stSplitXmlName);
                                        xwrSplit = new XmlTextWriter(stSplitXmlName, Encoding.UTF8);
                                        xwrSplit.WriteStartDocument();
                                        xwrSplit.WriteWhitespace("\r\n");
                                        xwrSplit.WriteStartElement("NewDataSet");
                                        xwrSplit.WriteWhitespace("\r\n");
                                    }
                                    //读取当前XML节点，到新的XML文件中
                                    xwrSplit.WriteNode(xrdSplit, false);
                                    //如果计数器已达到每页数据最大数据量时，计数器置零，关闭XML文件，并新建XML头
                                    if (Object.Equals(iCounters, iRowCounter))
                                    {
                                        lXmlCount += iCounters;

                                        iCounters = 0;
                                        lXmlCount = 0;
                                        xwrSplit.WriteEndElement();
                                        xwrSplit.WriteWhitespace("\r\n");
                                        xwrSplit.WriteEndDocument();
                                        xwrSplit.Flush();
                                        xwrSplit.Close();
                                    }
                                }
                                //当节点与缓存列表中的最后一位不等时,计数器置零,关闭XML文件，新建XML文件
                                else if (!Object.Equals((alsSplitXmlName[alsSplitXmlName.Count - 1]).ToString(), xrdSplit.Name.ToString()))
                                {
                                    alsSplitXmlName.Add(xrdSplit.Name.ToString());
                                    if (!Object.Equals(iCounters, 0))
                                    {
                                        lXmlCount += iCounters;

                                        xwrSplit.WriteEndElement();
                                        xwrSplit.WriteWhitespace("\r\n");
                                        xwrSplit.WriteEndDocument();
                                        xwrSplit.Flush();
                                        xwrSplit.Close();
                                    }
                                    iCounters = 0;
                                    lXmlCount = 0;
                                    iCounters++;
                                    stSplitXmlName = String.Format(stSystemp + "\\{0}.xml", Guid.NewGuid().ToString());
                                    alsSplitIndex.Add(stSplitXmlName);
                                    xwrSplit = new XmlTextWriter(stSplitXmlName, Encoding.UTF8);
                                    xwrSplit.WriteStartDocument();
                                    xwrSplit.WriteWhitespace("\r\n");
                                    xwrSplit.WriteStartElement("NewDataSet");
                                    xwrSplit.WriteWhitespace("\r\n\t");

                                    xwrSplit.WriteNode(xrdSplit, false);
                                }
                            }
                        }
                    }
                    if (!Object.Equals(iCounters, 0))
                    {
                        lXmlCount += iCounters;

                        xwrSplit.WriteEndElement();
                        xwrSplit.WriteWhitespace("\r\n");
                        xwrSplit.WriteEndDocument();
                        xwrSplit.Flush();
                        xwrSplit.Close();
                    }
                    xrdSplit.Close();
                    #endregion


                }
                else
                {
                    returnMessage.Message = "XML文件不正确，详细信息为：" + stErrMessage;
                    returnMessage.IsSucessed = bValid;
                }
                //删除原文件
                //File.Delete(xmlPath);


                //调用ValidData(string xmlSchemaPath)方法验证导入XML是否合法

                //判断bValid是否为false，若为false，则构造新的ReturnMessage，返回错误信息

                //若bValid为true,则开始对数据以XmlReader读取并进行插入。
                
                return returnMessage;
            }
            catch (Exception ex)
            {
                returnMessage.IsSucessed = false;
                returnMessage.Message = "拆分失败，失败原恩：" + ex.Message.ToString();
                return returnMessage;
            }
            
            
        }
        /// <summary>
        /// XML导入数据库
        /// </summary>
        /// <returns></returns>
        public ReturnMessage XmlInput(string stPath, string stXmlSchemaPath, string taskname)
        {
            ReturnMessage rm = new ReturnMessage(true);
            try
            {
                
                #region 导入数据库


                FileInfo[] files = DirectoryOperate.getAllFile(stPath, "*.xml");

                string str = ConfigurationManager.ConnectionStrings["APPDBSTRING"].ConnectionString.ToString();
                DataSet ds = new DataSet();
                ds.ReadXmlSchema(stXmlSchemaPath);
                foreach (FileInfo fileinfo in files)
                {
                    ds.ReadXml(fileinfo.FullName);
                    //声明数据库连接
                    SqlConnection conn = new SqlConnection(str);
                    conn.Open();
                    //声明SqlBulkCopy ,using释放非托管资源
                    using (SqlBulkCopy sqlBC = new SqlBulkCopy(conn))
                    {
                        //一次批量的插入的数据量
                        sqlBC.BatchSize = 1000;
                        //超时之前操作完成所允许的秒数，如果超时则事务不会提交 ，数据将回滚，所有已复制的行都会从目标表中移除
                        sqlBC.BulkCopyTimeout = 60;

                        //設定 NotifyAfter 属性，以便在每插入10000 条数据时，呼叫相应事件。  
                        sqlBC.NotifyAfter = 10000;
                        //sqlBC.SqlRowsCopied += new SqlRowsCopiedEventHandler(OnSqlRowsCopied);

                        foreach (DataTable dt in ds.Tables)
                        {
                            //设置要批量写入的表
                            sqlBC.DestinationTableName = "dbo.T_" + taskname + "_" + dt.TableName + "_Temp";

                            //自定义的datatable和数据库的字段进行对应
                            //sqlBC.ColumnMappings.Add("id", "tel");
                            //sqlBC.ColumnMappings.Add("name", "neirong");

                            //批量写入
                            sqlBC.WriteToServer(dt);
                        }
                    }
                    conn.Dispose();
                    ds.Clear();
                }
                #endregion
                return rm;
            }
            catch(Exception ex)
            {
                rm.IsSucessed = false;
                rm.Message = ex.Message;
                return rm;
            }
        }

        #endregion


    }
}
<file_sep>﻿using System;
using Service.Common.Entity;
using Service.Common.Log;
using System.Collections.Generic;
using System.Data;
namespace Message.Model
{
	/// <summary>
	/// MemberCard:实体类(属性说明自动提取数据库字段的描述信息)
	/// </summary>
    [TableAttribute("MemberCard")]
    public partial class MemberCard : EntityBase<MemberCard>
	{
		public MemberCard()
		{}
		#region Model
		private int _id;
		private string _cardno;
		private int _cardtype;
		private string _membername;
		private string _password;
		private string _usertel;
		private string _userpic;
		private decimal _balance;
		private DateTime _handletime= DateTime.Now;
		private DateTime _lastuse= DateTime.Now;
		private int _state;
		private string _remarks;
		/// <summary>
		/// ID
		/// </summary>
        [PrimaryKey("ID", IsAuto = true)]
        public int ID
		{
			set{ _id=value;}
			get{return _id;}
		}
		/// <summary>
		/// 会员卡号
        /// </summary>
        [Property]
		public string CardNO
		{
			set{ _cardno=value;}
			get{return _cardno;}
		}
		/// <summary>
		/// 会员卡类型
        /// </summary>
        [Property]
		public int CardType
		{
			set{ _cardtype=value;}
			get{return _cardtype;}
		}
		/// <summary>
		/// 用户姓名
        /// </summary>
        [Property]
		public string MemberName
		{
			set{ _membername=value;}
			get{return _membername;}
		}
		/// <summary>
		/// 密码
        /// </summary>
        [Property]
		public string PassWord
		{
			set{ _password=value;}
			get{return _password;}
		}
		/// <summary>
		/// 联系电话
        /// </summary>
        [Property]
		public string UserTel
		{
			set{ _usertel=value;}
			get{return _usertel;}
		}
		/// <summary>
		/// 照片
        /// </summary>
        [Property]
		public string UserPic
		{
			set{ _userpic=value;}
			get{return _userpic;}
		}
		/// <summary>
		/// 余额
        /// </summary>
        [Property]
		public decimal Balance
		{
			set{ _balance=value;}
			get{return _balance;}
		}
		/// <summary>
		/// 办理时间
        /// </summary>
        [Property]
		public DateTime HandleTime
		{
			set{ _handletime=value;}
			get{return _handletime;}
		}
		/// <summary>
		/// 最后一次使用
        /// </summary>
        [Property]
		public DateTime LastUse
		{
			set{ _lastuse=value;}
			get{return _lastuse;}
		}
		/// <summary>
		/// 状态 1：可用，0：不可用
        /// </summary>
        [Property]
		public int State
		{
			set{ _state=value;}
			get{return _state;}
		}
		/// <summary>
		/// 备注
        /// </summary>
        [Property]
		public string Remarks
		{
			set{ _remarks=value;}
			get{return _remarks;}
		}
		#endregion Model

	}

    public static class MemCardOper
    {

        /// <summary>
        /// 
        /// </summary>
        /// <param name="CardNumber">会员卡号</param>
        /// <param name="ConsumptionAmount">消费金额</param>
        /// <param name="TradeNo">交易号</param>
        /// <returns></returns>
        public static ReturnMessage MemCardHandle(string CardNumber, decimal ConsumptionAmount, string TradeNo)
        {
            ReturnMessage rm = new ReturnMessage();
            List<string[]> liWhere = new List<string[]>();
            liWhere.Add(new string[] { "CardNO = {0}", CardNumber });
            MemberCard mc = new MemberCard();
            DataTable dt = mc.GetDataSet("SELECT TOP 1 ID FROM MemberCard", liWhere);
            string MbID;
            if (dt.Rows.Count > 0)
            {
                MbID = dt.Rows[0][0].ToString();
                mc.FindbyPK(MbID);
                mc.Balance -= ConsumptionAmount;
                mc.LastUse = DateTime.Now;
                rm = mc.Update();

                if (!rm.IsSucessed)
                {
                    rm.Message += "更新会员卡信息出错！";
                    return rm;
                }
                else
                {
                    ConsumptionRecords cr = new ConsumptionRecords();
                    cr.CardID = mc.ID;
                    cr.RecType = 0;
                    cr.Amount = ConsumptionAmount;
                    cr.TradeNo = TradeNo;
                    cr.OpeTime = DateTime.Now;
                    cr.Insert();
                    return rm;
                }
            }
            else
            {
                rm.IsSucessed = false;
                rm.Message = "读取会员卡信息出错！";
                return rm;
            }
        }
    }
}

<file_sep>﻿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 WinApp.WinForm.Report;
using Service.Common.Data;
using Message.Model;
using System.Threading;
using Service.Common;

namespace WinApp.WinForm
{
    public partial class FormShift : Form
    {
        Sale_Detail sd = new Sale_Detail();
        Int32 ShiftID = 0;
        public FormShift(Int32 shiftid)
        {
            ShiftID = shiftid;
            InitializeComponent();
            dataGridView1.AutoGenerateColumns = false;
            dgvDetail.AutoGenerateColumns = false;
            ucPage1.DataSetSql = "SELECT * FROM v_SaleList";
            ucPage1.LiWhere.Add(new string[] { "State = {0}", "0" });
            ucPage2.DataSetSql = "SELECT * FROM v_SaleDetailList";
            ucPage2.LiWhere.Add(new string[] { "State = {0}", "0" });
            
            GetLiWhere(ShiftID);

            ucPage1.LiOrder.Add(new string[] { "Sale_ID", "DESC" });
            dataGridView1.DataSource = ucPage1.GetDataTable();
            ucPage2.LiOrder.Add(new string[] { "Sale_Detail_ID", "DESC" });
            dgvDetail.DataSource = ucPage2.GetDataTable();
            ucPage1.PageEvent += new WinApp.Controls.PageEntrust(ucPage1_PageEvent);
            ucPage2.PageEvent += new WinApp.Controls.PageEntrust(ucPage2_PageEvent);
            Sale SaleInfo = new Sale();
            DataTable dt = SaleInfo.GetDataSet("SELECT SUM(TotalAmount) AS Total,SUM(Cash) AS Cash,SUM(MemCard) AS MemCard,SUM(UnionPay) AS UnionPay,SUM(OtherPayment) AS OtherPayment FROM Sale", ucPage1.LiWhere);
            lbTotalAmount.Text = dt.Rows[0]["Total"].ToString();
            lbCash.Text = dt.Rows[0]["Cash"].ToString();
            lbMembershipCard.Text = dt.Rows[0]["MemCard"].ToString();
            lbUnionPay.Text = dt.Rows[0]["UnionPay"].ToString();
            lbOther.Text = dt.Rows[0]["OtherPayment"].ToString();
            DataTable dt1 = SaleInfo.GetDataSet("SELECT SUM(Commission) AS Commission FROM v_SaleDetailList", ucPage1.LiWhere);
            lbCommission.Text = dt1.Rows[0][0].ToString();



            ControlCommon.BindEmployee(cbServer);
            DataTable dt2 = (DataTable)cbServer.DataSource;
            DataRow dr = dt2.NewRow();
            dr["Employee_ID"] = 0;
            dr["Name"] = "<—全部—>";
            dt2.Rows.InsertAt(dr, 0);
            cbServer.SelectedIndex = 0;
            ControlCommon.BindProduct(cbProName);
            DataTable dt3 = (DataTable)cbProName.DataSource;
            DataRow dr1 = dt3.NewRow();
            dr1["Product_ID"] = 0;
            dr1["Name"] = "<—全部—>";
            dt3.Rows.InsertAt(dr1, 0);
            cbProName.SelectedIndex = 0;

            GetDtlTotalAmount();

        }




        void ucPage1_PageEvent()
        {
            dataGridView1.DataSource = ucPage1.GetDataTable();
        }
        void ucPage2_PageEvent()
        {
            dgvDetail.DataSource = ucPage2.GetDataTable();
        }

        private void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            FormSaleDetail fsd = new FormSaleDetail(Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells["Sale_ID"].Value));
            fsd.ShowDialog(this);
        }

        private void btnShift_Click(object sender, EventArgs e)
        {
            if (((DataTable)(dataGridView1.DataSource)).Rows.Count > 0)
            {
                if (MessageBox.Show("确定要清帐交接吗？", "确定", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) == DialogResult.Yes)
                {
                    ShiftInfo si = new ShiftInfo();
                    DataSet ds = ExecuteSql.ExeComSqlForDataSet("SELECT TOP 1 StartID,EndID,StartTime,EndTime FROM ShiftInfo ORDER BY ID DESC");
                    DataSet ds1 = ExecuteSql.ExeComSqlForDataSet("SELECT TOP 1 Sale_ID,CheckoutTime FROM Sale WHERE Sale_ID > " + ds.Tables[0].Rows[0]["EndID"].ToString() + " AND State = 0 ORDER BY Sale_ID ASC");
                    DataSet ds2 = ExecuteSql.ExeComSqlForDataSet("SELECT TOP 1 Sale_ID,CheckoutTime FROM Sale WHERE Sale_ID > " + ds.Tables[0].Rows[0]["EndID"].ToString() + " AND State = 0 ORDER BY Sale_ID DESC");
                    si.StartID = Convert.ToInt32(ds1.Tables[0].Rows[0]["Sale_ID"]);
                    si.StartTime = Convert.ToDateTime(ds1.Tables[0].Rows[0]["CheckoutTime"]);
                    si.EndID = Convert.ToInt32(ds2.Tables[0].Rows[0]["Sale_ID"]);
                    si.EndTime = Convert.ToDateTime(ds2.Tables[0].Rows[0]["CheckoutTime"]);
                    si.ShiftTime = DateTime.Now;
                    si.ShiftUser = Convert.ToInt32(Thread.CurrentPrincipal.Identity.Name);
                    si.Insert();
                    MessageBox.Show("操作成功！");
                    DialogResult = DialogResult.OK;
                }
            }
            else
            {
                MessageBox.Show("没有销售记录不能交班！");
            }
        }

        private void btnDtlSearch_Click(object sender, EventArgs e)
        {
            ucPage2.LiWhere.Clear();
            ucPage2.LiWhere.Add(new string[] { "State = {0}", "0" });
            GetLiWhere(ShiftID);
            if (cbProName.SelectedValue.ToString() != "0")
            {
                ucPage2.LiWhere.Add(new string[] { "Product_ID ={0}", cbProName.SelectedValue.ToString() });
            }
            if (cbServer.SelectedValue.ToString() != "0")
            {
                ucPage2.LiWhere.Add(new string[] { "Employee_ID = {0}", cbServer.SelectedValue.ToString() });
            }
            if (tbxOrderNoDtl.Text.Trim() != "")
            {
                ucPage2.LiWhere.Add(new string[] { "OrderNo LIKE '%' + {0} + '%'", tbxOrderNoDtl.Text.Trim() });
            }
            ucPage2.CurPage = 1;
            dgvDetail.DataSource = ucPage2.GetDataTable();
            GetDtlTotalAmount();
        }

        private void GetDtlTotalAmount()
        {
            DataTable dt = sd.GetDataSet("SELECT SUM(Total),SUM(Commission) FROM v_SaleDetailList", ucPage2.LiWhere);
            if (dt.Rows[0][0] != System.DBNull.Value)
            {
                lbTotalAmountDtl.Text = (Convert.ToDecimal(dt.Rows[0][0])).ToString("f2") + " 元";
                lbCommissionDtl.Text = (Convert.ToDecimal(dt.Rows[0][1])).ToString("f2") + " 元";
            }
            else
            {
                lbTotalAmountDtl.Text = "0 元";
                lbCommissionDtl.Text = "0 元";
            }
        }

        private void GetLiWhere(Int32 ShiftID)
        {
            if (ShiftID == 0)
            {
                DataSet ds = ExecuteSql.ExeComSqlForDataSet("SELECT TOP 1 StartID,EndID,StartTime,EndTime FROM ShiftInfo ORDER BY ID DESC");
                ucPage1.LiWhere.Add(new string[] { "Sale_ID > {0}", ds.Tables[0].Rows[0]["EndID"].ToString() });
                ucPage2.LiWhere.Add(new string[] { "Sale_ID > {0}", ds.Tables[0].Rows[0]["EndID"].ToString() });
            }
            else
            {
                ShiftInfo si = new ShiftInfo();
                si.FindbyPK(ShiftID.ToString());
                ucPage1.LiWhere.Add(new string[] { "Sale_ID >= {0}", si.StartID.ToString() });
                ucPage1.LiWhere.Add(new string[] { "Sale_ID <= {0}", si.EndID.ToString() });
                ucPage2.LiWhere.Add(new string[] { "Sale_ID >= {0}", si.StartID.ToString() });
                ucPage2.LiWhere.Add(new string[] { "Sale_ID <= {0}", si.EndID.ToString() });
                btnShift.Visible = false;
            }
        }

    }
}
<file_sep>﻿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 Message.Model;
using Service.Common;

namespace WinApp.WinForm.Admin
{
    public partial class FormCreateCard : Form
    {
        MemberCard mc = new MemberCard();
        public FormCreateCard()
        {
            InitializeComponent();
            ControlCommon.BindCardType(cbCardType);
        }

        private void btnDetermine_Click(object sender, EventArgs e)
        {
            if (tbxCardNO.Text.Trim() == "")
            {
                MessageBox.Show("请填写卡号！");
                tbxCardNO.Focus();
                return;
            }
            if (this.tbxMemberName.Text.Trim() == "")
            {
                MessageBox.Show("请填写用户姓名！");
                tbxMemberName.Focus();
                return;
            }
            if (this.tbxUserTel.Text.Trim() == "")
            {
                MessageBox.Show("请填写电话！");
                tbxUserTel.Focus();
                return;
            }
            
            List<string[]> liWhere = new List<string[]>();
            liWhere.Add(new string[] { "CardNO = {0}", tbxCardNO.Text });
            if (mc.GetDataSetCount("SELECT ID FROM MemberCard", liWhere) > 0)
            {
                MessageBox.Show("该卡号已经存在！");
                return;
            }
            mc.CardNO = tbxCardNO.Text;
            mc.CardType = Convert.ToInt32(cbCardType.SelectedValue);
            mc.MemberName = tbxMemberName.Text;
            mc.UserTel = tbxUserTel.Text;
            mc.PassWord = "";
            mc.UserPic = "";
            mc.Balance = 0;
            mc.HandleTime = DateTime.Now;
            mc.LastUse = DateTime.Now;
            mc.State = 1;
            mc.Remarks = tbxRemarks.Text;
            if (mc.Insert().IsSucessed)
            {
                MessageBox.Show("办卡成功！");
                DialogResult = DialogResult.OK;
            }
        }

        private void btnCancle_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
        }
    }
}
<file_sep>﻿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 WinApp.WinForm.Report
{
    public partial class FormSaleList : Form
    {
        public FormSaleList()
        {
            InitializeComponent();
            dataGridView1.AutoGenerateColumns = false;
            dataGridView2.AutoGenerateColumns = false;
        }

        private void FormSaleList_Load(object sender, EventArgs e)
        {
            ucPage1.DataSetSql = "SELECT * FROM v_SaleList";
            ucPage1.LiWhere.Add(new string[] { "State = {0}", "0" });
            ucPage1.LiOrder.Add(new string[] { "Sale_ID", "DESC" });
            dataGridView1.DataSource = ucPage1.GetDataTable();

            ucPage2.DataSetSql = "SELECT ID,StartTime,EndTime,ShiftUser,Name,ShiftTime,'～' AS WaveLine FROM ShiftInfo LEFT JOIN Employee ON ShiftUser = Employee_ID";
            //ucPage2.LiWhere.Add(new string[] { "1={0}", "1" });
            ucPage2.LiOrder.Add(new string[] { "y.ID", "DESC" });
            dataGridView2.DataSource = ucPage2.GetDataTable();
            ucPage1.PageEvent += new WinApp.Controls.PageEntrust(ucPage1_PageEvent);
            ucPage2.PageEvent += new WinApp.Controls.PageEntrust(ucPage2_PageEvent);
        }

        void ucPage1_PageEvent()
        {
            dataGridView1.DataSource = ucPage1.GetDataTable();
        }

        void ucPage2_PageEvent()
        {
            dataGridView2.DataSource = ucPage2.GetDataTable();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            ucPage1.LiWhere.Clear();
            ucPage1.LiWhere.Add(new string[] { "State = {0}", "0" });
            if (dtpFrom.Checked)
            {
                ucPage1.LiWhere.Add(new string[] { "CheckoutTime > {0}", dtpFrom.Value.ToShortDateString() });
            }
            if (dtpTo.Checked)
            {
                ucPage1.LiWhere.Add(new string[] { "CheckoutTime < {0}", dtpTo.Value.AddDays(1).ToShortDateString() });
            }
            if (tbxTradCode.Text.Trim() != "")
            {
                ucPage1.LiWhere.Add(new string[] { "TradeNo LIKE '%' + {0} + '%'", tbxTradCode.Text.Trim() });
            }
            if (tbxOrderNo.Text.Trim() != "")
            {
                ucPage1.LiWhere.Add(new string[] { "OrderNo LIKE '%' + {0} + '%'", tbxOrderNo.Text.Trim() });
            }
            ucPage1.CurPage = 1;
            dataGridView1.DataSource = ucPage1.GetDataTable();
        }

        private void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            FormSaleDetail fsd = new FormSaleDetail(Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells["Sale_ID"].Value));
            fsd.ShowDialog(this);
        }

        private void dataGridView2_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            FormShift fs = new FormShift(Convert.ToInt32(dataGridView2.Rows[dataGridView2.CurrentCell.RowIndex].Cells["ShiftID"].Value));
            fs.ShowDialog();
        }

    }
}
<file_sep>﻿using System;
using Service.Common.Entity;
namespace Message.Model
{
	/// <summary>
	/// Product:实体类(属性说明自动提取数据库字段的描述信息)
	/// </summary>
    [TableAttribute("Product")]
    public partial class Product : EntityBase<Product>
	{
		public Product()
		{}
		#region Model
		private int _product_id;
		private string _code;
		private int _productlist_id;
		private string _name;
		private string _shortname;
		private string _spell;
		private string _s_spell;
		private int _productspec_id;
		private int _productunit_id;
		private decimal _price;
		private decimal _offering_price;
        private decimal _commission;
		private int _employee_id;
		private DateTime _createdate= DateTime.Now;
		private string _remark;
		/// <summary>
		/// ID
		/// </summary>
        [PrimaryKey("Product_ID", IsAuto = true)]
		public int Product_ID
		{
			set{ _product_id=value;}
			get{return _product_id;}
		}
		/// <summary>
		/// 商品编号
        /// </summary>
        [Property]
		public string Code
		{
			set{ _code=value;}
			get{return _code;}
		}
		/// <summary>
		/// 
        /// </summary>
        [Property]
		public int ProductList_ID
		{
			set{ _productlist_id=value;}
			get{return _productlist_id;}
		}
		/// <summary>
		/// 商品名称
        /// </summary>
        [Property]
		public string Name
		{
			set{ _name=value;}
			get{return _name;}
		}
		/// <summary>
		/// 名称简写
        /// </summary>
        [Property]
		public string shortname
		{
			set{ _shortname=value;}
			get{return _shortname;}
		}
		/// <summary>
		/// 拼音全拼
        /// </summary>
        [Property]
		public string spell
		{
			set{ _spell=value;}
			get{return _spell;}
		}
		/// <summary>
		/// 拼音简写
        /// </summary>
        [Property]
		public string s_spell
		{
			set{ _s_spell=value;}
			get{return _s_spell;}
		}
		/// <summary>
		/// 部门ID
        /// </summary>
        [Property]
		public int ProductSpec_ID
		{
			set{ _productspec_id=value;}
			get{return _productspec_id;}
		}
		/// <summary>
		/// 类型ID
        /// </summary>
        [Property]
		public int ProductUnit_ID
		{
			set{ _productunit_id=value;}
			get{return _productunit_id;}
		}
		/// <summary>
		/// 价格
        /// </summary>
        [Property]
		public decimal Price
		{
			set{ _price=value;}
			get{return _price;}
		}
		/// <summary>
		/// 折扣价格
        /// </summary>
        [Property]
		public decimal Offering_Price
		{
			set{ _offering_price=value;}
			get{return _offering_price;}
		}

        /// <summary>
        /// 提成
        /// </summary>
        [Property]
        public decimal Commission
        {
            get { return _commission; }
            set { _commission = value; }
        }
		/// <summary>
		/// 操作员
        /// </summary>
        [Property]
		public int Employee_ID
		{
			set{ _employee_id=value;}
			get{return _employee_id;}
		}
		/// <summary>
		/// 创建日期
        /// </summary>
        [Property]
		public DateTime CreateDate
		{
			set{ _createdate=value;}
			get{return _createdate;}
		}
		/// <summary>
		/// 备注
        /// </summary>
        [Property]
		public string Remark
		{
			set{ _remark=value;}
			get{return _remark;}
		}
		#endregion Model

	}
}

<file_sep>﻿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 Service.Common.Data;

namespace WinApp
{
    public partial class test : Form
    {
        public test()
        {
            InitializeComponent();
        }

        private void test_Load(object sender, EventArgs e)
        {
            dataGridView1.AutoGenerateColumns = false;
            DataGridViewComboBoxColumn dgvComboBoxColumn = (DataGridViewComboBoxColumn)this.dataGridView1.Columns["Discount"];
            dgvComboBoxColumn.DataPropertyName = "Discount";
            dgvComboBoxColumn.DataSource = ExecuteSql.ExeComSqlForDataSet("SELECT DiscountRate,DisName FROM Discount WHERE Available = 1").Tables[0];
            dgvComboBoxColumn.DisplayMember = "DisName";
            dgvComboBoxColumn.ValueMember = "DiscountRate";

            DataTable dt = ExecuteSql.ExeComSqlForDataSet("SELECT * FROM dbo.v_SaleDetailList WHERE SaleOrder_ID = 88").Tables[0];
            dataGridView1.DataSource = dt;
        }

        private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            decimal TotalAmount = 0;
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                TotalAmount += Convert.ToDecimal(dataGridView1.Rows[i].Cells["PaidIn"].Value);
            }
            //lbTotal.Text = TotalAmount.ToString();
        }

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            if (e.RowIndex >= dataGridView1.FirstDisplayedScrollingRowIndex)
            {
                using (SolidBrush b = new SolidBrush(dataGridView1.RowHeadersDefaultCellStyle.ForeColor))
                {
                    int linen = 0;
                    linen = e.RowIndex + 1;
                    string line = linen.ToString();
                    e.Graphics.DrawString(line, e.InheritedRowStyle.Font, b, e.RowBounds.Location.X, e.RowBounds.Location.Y + 5);
                    SolidBrush B = new SolidBrush(Color.Red);
                }
            }
        }
    }
}
<file_sep>﻿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 Service.Common.Data;
using Message.Model;
using Service.Common;

namespace WinApp.WinForm.Admin
{
    public partial class FormAdmin : Form
    {
        Discount dct = new Discount();
        CardType ct = new CardType();
        public FormAdmin()
        {
            InitializeComponent();
        }

        private void tabPage1_Enter(object sender, EventArgs e)
        {
            dgvEmployee.AutoGenerateColumns = false;
            ucPage1.DataSetSql = "SELECT * FROM Employee";
            ucPage1.LiOrder.Add(new string[] { "Employee_ID", "ASC" });
            ucPage2.LiOrder.Add(new string[] { "Product_ID", "DESC" });
            dgvEmployee.DataSource = ucPage1.GetDataTable();
            ucPage1.PageEvent += new WinApp.Controls.PageEntrust(ucPage1_PageEvent);
        }

        void ucPage1_PageEvent()
        {
            dgvEmployee.DataSource = ucPage1.GetDataTable();
        }

        private void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            FormEmpDtl fed = new FormEmpDtl(Convert.ToInt32(dgvEmployee.Rows[dgvEmployee.CurrentCell.RowIndex].Cells["Employee_ID"].Value));
            if (fed.ShowDialog() == DialogResult.OK)
            {
                MessageBox.Show("修改成功！");
                dgvEmployee.DataSource = ucPage1.GetDataTable();
            }
        }

        private void btnNewUser_Click(object sender, EventArgs e)
        {
            FormEmpDtl fed = new FormEmpDtl(0);
            if (fed.ShowDialog() == DialogResult.OK)
            {
                MessageBox.Show("保存成功！");
                dgvEmployee.DataSource = ucPage1.GetDataTable();
            }
        }

        private void tabPage2_Enter(object sender, EventArgs e)
        {
            dgvProduct.AutoGenerateColumns = false;
            ucPage2.DataSetSql = "SELECT * FROM Product";
            dgvProduct.DataSource = ucPage2.GetDataTable();
            ucPage2.PageEvent += new WinApp.Controls.PageEntrust(ucPage2_PageEvent);
        }
        void ucPage2_PageEvent()
        {
            dgvProduct.DataSource = ucPage2.GetDataTable();
        }

        private void dgvProduct_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            FormProdDtl fpd = new FormProdDtl(Convert.ToInt32(dgvProduct.Rows[dgvProduct.CurrentCell.RowIndex].Cells["Product_ID"].Value));
            if (fpd.ShowDialog() == DialogResult.OK)
            {
                dgvProduct.DataSource = ucPage2.GetDataTable();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            FormProdDtl fpd = new FormProdDtl(0);
            if (fpd.ShowDialog() == DialogResult.OK)
            {
                dgvProduct.DataSource = ucPage2.GetDataTable();
            }
        }

        private void tabPage3_Enter(object sender, EventArgs e)
        {
            BindDiscount();
        }

        private void BindDiscount()
        {
            dgvDiscount.AutoGenerateColumns = false;
            DataSet dsDiscount = ExecuteSql.ExeComSqlForDataSet("SELECT * FROM Discount");
            dgvDiscount.DataSource = dsDiscount.Tables[0];
        }

        private void dgvDiscount_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            if (e.RowIndex >= dgvDiscount.FirstDisplayedScrollingRowIndex)
            {
                using (SolidBrush b = new SolidBrush(dgvDiscount.RowHeadersDefaultCellStyle.ForeColor))
                {
                    int linen = 0;
                    linen = e.RowIndex + 1;
                    string line = linen.ToString();
                    e.Graphics.DrawString(line, e.InheritedRowStyle.Font, b, e.RowBounds.Location.X, e.RowBounds.Location.Y + 5);
                    SolidBrush B = new SolidBrush(Color.Red);
                }
            }
        }

        private void dgvDiscount_SelectionChanged(object sender, EventArgs e)
        {
            getDiscountDtl();
        }

        private void getDiscountDtl()
        {
            dct.FindbyPK(dgvDiscount.Rows[dgvDiscount.CurrentCell.RowIndex].Cells["DiscountID"].Value.ToString());
            tbxDisName.Text = dct.DisName;
            tbxDiscountRate.Text = dct.DiscountRate.ToString("f2");
            if (dct.Available)
            {
                rbAvailable.Checked = true;
            }
            else
            {
                rbNotAvailable.Checked = true;
            }
        }

        private void btnSaveDiscount_Click(object sender, EventArgs e)
        {
            Int32 selectRow = 0;
            if (dgvDiscount.CurrentCell.RowIndex >= 0)
            {
                selectRow = dgvDiscount.CurrentCell.RowIndex;
            }
            dct.FindbyPK(dgvDiscount.Rows[dgvDiscount.CurrentCell.RowIndex].Cells["DiscountID"].Value.ToString());
            dct.DisName = tbxDisName.Text;
            dct.DiscountRate = Convert.ToDecimal(tbxDiscountRate.Text);
            if (rbAvailable.Checked)
            {
                dct.Available = true;
            }
            else
            {
                dct.Available = false;
            }
            dct.Update();
            BindDiscount();
            dgvDiscount.CurrentCell = dgvDiscount[0, selectRow];
            getDiscountDtl();
        }

        private void tbxDiscountRate_KeyPress(object sender, KeyPressEventArgs e)
        {
            ControlCommon.VerDecimal(sender, e);
        }

        private void btnAddDiscount_Click(object sender, EventArgs e)
        {
            FormAddDiscount fad = new FormAddDiscount();
            fad.ShowDialog();
            BindDiscount();
        }

        private void tabPage4_Enter(object sender, EventArgs e)
        {
            BindCardType();
        }

        private void BindCardType()
        {
            dgvCardType.AutoGenerateColumns = false;
            DataSet dsCardType = ExecuteSql.ExeComSqlForDataSet("SELECT ID, TypeName, Discount, CASE Available WHEN 1 THEN '可用' WHEN 0 THEN '不可用' END AS Available  FROM CardType");
            dgvCardType.DataSource = dsCardType.Tables[0];
            ControlCommon.BindDiscount(cbDiscount);
        }

        private void dgvCardType_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            if (e.RowIndex >= dgvCardType.FirstDisplayedScrollingRowIndex)
            {
                using (SolidBrush b = new SolidBrush(dgvCardType.RowHeadersDefaultCellStyle.ForeColor))
                {
                    int linen = 0;
                    linen = e.RowIndex + 1;
                    string line = linen.ToString();
                    e.Graphics.DrawString(line, e.InheritedRowStyle.Font, b, e.RowBounds.Location.X, e.RowBounds.Location.Y + 5);
                    SolidBrush B = new SolidBrush(Color.Red);
                }
            }
        }

        private void dgvCardType_SelectionChanged(object sender, EventArgs e)
        {
            getCardTypeDtl();
        }

        private void getCardTypeDtl()
        {
            ct.FindbyPK(dgvCardType.Rows[dgvCardType.CurrentCell.RowIndex].Cells["CardTypeID"].Value.ToString());
            tbxCardTypeName.Text = ct.TypeName;
            cbDiscount.SelectedValue = ct.Discount;
            if (ct.Available == 1)
            {
                rbctAvailable.Checked = true;
            }
            else
            {
                rbctNotAvailable.Checked = true;
            }
        }

        private void btnCreateType_Click(object sender, EventArgs e)
        {
            FormCreateCardType fcct = new FormCreateCardType();
            if (fcct.ShowDialog() == DialogResult.OK)
            {
                BindCardType();
            }
        }

        private void btnSaveCardType_Click(object sender, EventArgs e)
        {
            Int32 selectRow = 0;
            if (dgvCardType.CurrentCell.RowIndex >= 0)
            {
                selectRow = dgvCardType.CurrentCell.RowIndex;
            }
            ct.FindbyPK(dgvCardType.Rows[dgvCardType.CurrentCell.RowIndex].Cells["CardTypeID"].Value.ToString());
            ct.TypeName = tbxCardTypeName.Text;
            ct.Discount = Convert.ToDecimal(cbDiscount.SelectedValue);
            if (rbctAvailable.Checked)
            {
                ct.Available = 1;
            }
            else
            {
                ct.Available = 0;
            }
            ct.Update();
            BindCardType();
            dgvCardType.CurrentCell = dgvCardType[0, selectRow];
            getCardTypeDtl();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            ucPage2.LiWhere.Clear();
            if (!string.IsNullOrEmpty(tbxProCode.Text.Trim()))
            {
                ucPage2.LiWhere.Add(new string[] { "Code LIKE '%' + {0} + '%'", tbxProCode.Text.Trim() });
            }
            if (!string.IsNullOrEmpty(tbxProName.Text.Trim()))
            {
                ucPage2.LiWhere.Add(new string[] { "Name LIKE '%' + {0} + '%'", tbxProName.Text.Trim() });
            }
            if (!string.IsNullOrEmpty(tbxPinYin.Text.Trim()))
            {
                ucPage2.LiWhere.Add(new string[] { "(spell LIKE '%' + {0} + '%' OR s_spell LIKE '%' + {0} + '%')", tbxPinYin.Text.Trim() });
            }
            dgvProduct.DataSource = ucPage2.GetDataTable();
        }

        private void tbxProCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            ControlCommon.VerDigital(e);
        }
    }
}
<file_sep>﻿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 Message.Model;
using Service.Common;

namespace WinApp.WinForm
{
    public partial class FormCashier : Form
    {
        Sale SaleInfo = new Sale();
        PaymentInfo paymentInfo = new PaymentInfo();

        public PaymentInfo PaymentInfo
        {
            get { return paymentInfo; }
            set { paymentInfo = value; }
        }
        public FormCashier(Int32 Sale_ID)
        {
            InitializeComponent();
            SaleInfo.FindbyPK(Sale_ID.ToString());
            tbxAmount.Text = SaleInfo.TotalAmount.ToString("f2");
            tbxCash.Text = SaleInfo.TotalAmount.ToString("f2");
        }



        private void btnEnter_Click(object sender, EventArgs e)
        {
            if (tbxAmount.Text.Trim()!="")
            {
                if (Convert.ToDecimal(tbxAmount.Text) == Convert.ToDecimal(tbxCash.Text) + Convert.ToDecimal(tbxUnionPay.Text) + Convert.ToDecimal(tbxOtherPayment.Text) + Convert.ToDecimal(tbxCardPayment.Text))
                {
                    paymentInfo.TotalAmount = Convert.ToDecimal(tbxAmount.Text);
                    paymentInfo.Cash = Convert.ToDecimal(tbxCash.Text);
                    paymentInfo.UnionPay = Convert.ToDecimal(tbxUnionPay.Text);
                    paymentInfo.OtherPayment = Convert.ToDecimal(tbxOtherPayment.Text);
                    paymentInfo.MemCard = Convert.ToDecimal(tbxCardPayment.Text);
                    this.DialogResult = DialogResult.OK;
                }
                else
                {
                    MessageBox.Show("消费数额填写有误！");
                }
            }
            else
            {
                MessageBox.Show("请填写消费金额！");
            }
        }

        private void btnChooseCard_Click(object sender, EventArgs e)
        {
            if (tbxAmount.Text.Trim()!="")
            {
                FormMemCard fmc = new FormMemCard(Convert.ToDecimal(tbxAmount.Text));
                if (fmc.ShowDialog() == DialogResult.OK)
                {
                    tbxCardPayment.Text = fmc.PaymentCard.ToString("f2");
                    ClearAllText();
                    tbxCash.Text = (Convert.ToDecimal(tbxAmount.Text) - Convert.ToDecimal(tbxCardPayment.Text)).ToString("f2");
                    lbCardNo.Text = "No：" + fmc.CardNo;
                    paymentInfo.Account = fmc.CardNo;
                    lbCardNo.Visible = true;
                }
            }
            else
            {
                MessageBox.Show("请填写消费金额！");
            }
        }

        private void ClearAllText()
        {
            tbxCash.Text = "0.00";
            tbxUnionPay.Text = "0.00";
            tbxOtherPayment.Text = "0.00";
        }


        private void tbxAmount_KeyUp(object sender, KeyEventArgs e)
        {
            if (tbxAmount.Text.Trim()!="")
            {
                ClearAllText();
                decimal cash = Convert.ToDecimal(tbxAmount.Text) - Convert.ToDecimal(tbxCardPayment.Text);
                if (cash >= 0)
                {
                    tbxCash.Text = cash.ToString("f2");
                }
                tbxAmount.Focus();
            }
            else
            {
                ClearAllText();
                tbxAmount.Focus();
            }
        }

        private void tbxAmount_KeyPress(object sender, KeyPressEventArgs e)
        {
            ControlCommon.VerDecimal(sender, e);
        }

        private void tbxCash_KeyPress(object sender, KeyPressEventArgs e)
        {
            ControlCommon.VerDecimal(sender, e);
        }

        private void tbxUnionPay_KeyPress(object sender, KeyPressEventArgs e)
        {
            ControlCommon.VerDecimal(sender, e);
        }

        private void tbxOtherPayment_KeyPress(object sender, KeyPressEventArgs e)
        {
            ControlCommon.VerDecimal(sender, e);
        }
    }
}
<file_sep>﻿using System;
using Service.Common.Entity;
namespace Message.Model
{
	/// <summary>
	/// UserRole:实体类(属性说明自动提取数据库字段的描述信息)
	/// </summary>
    [TableAttribute("UserRole")]
    public partial class UserRole : EntityBase<UserRole>
	{
		public UserRole()
		{}
		#region Model
		private int _roleid;
		private int _rights;
		/// <summary>
		/// 
		/// </summary>
        [Property]
        public int RoleId
		{
            set { _roleid = value; }
            get { return _roleid; }
		}
		/// <summary>
		/// 
        /// </summary>
        [Property]
		public int Rights
		{
			set{ _rights=value;}
			get{return _rights;}
		}
		#endregion Model

	}
}

<file_sep>﻿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 System.Configuration;

namespace WinApp.WinForm
{
    public partial class FormBackPassword : Form
    {
        public FormBackPassword()
        {
            InitializeComponent();
        }

        private void btnDetermine_Click(object sender, EventArgs e)
        {
            if (tbxBackPwd.Text != "")
            {
                if (ConfigurationManager.AppSettings.Get("BackPwd") == tbxBackPwd.Text.Trim())
                {
                    DialogResult = DialogResult.OK;
                }
                else
                {
                    lbWrongPwd.Visible = true;
                }
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
        }
    }
}<file_sep>﻿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 Message.Model;
using System.Threading;
using Service.Common;

namespace WinApp.WinForm.Admin
{
    public partial class FormSetting : Form
    {
        public FormSetting()
        {
            InitializeComponent();
        }

        private void btnDetermine_Click(object sender, EventArgs e)
        {
            Employee emp = new Employee();
            emp.FindbyPK(Thread.CurrentPrincipal.Identity.Name);
            if (tbxOriginalPwd.Text.Trim() != "")
            {
                if (DecryptEncrypt.EncryptText(tbxOriginalPwd.Text) == emp.PassWord)
                {
                    if (tbxNewPwd.Text.Trim() != "")
                    {
                        if (tbxNewPwdConfirm.Text.Trim() != "")
                        {
                            if (tbxNewPwd.Text.Trim() == tbxNewPwdConfirm.Text.Trim())
                            {
                                emp.PassWord = DecryptEncrypt.EncryptText(tbxNewPwd.Text.Trim());
                                emp.Update();
                                MessageBox.Show("密码修改成功！");
                                Close();
                            }
                            else
                            {
                                MessageBox.Show("两次新密码不一样！");
                            }
                        }
                        else
                        {
                            MessageBox.Show("请填写确认新密码！");
                            tbxNewPwdConfirm.Focus();
                        }
                    }
                    else
                    {
                        MessageBox.Show("请填写新密码！");
                        tbxNewPwd.Focus();
                    }
                }
                else
                {
                    MessageBox.Show("原密码不正确！");
                    tbxOriginalPwd.Focus();
                }
            }
            else
            {
                MessageBox.Show("请填写原密码！");
                tbxOriginalPwd.Focus();
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}
<file_sep>﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WinApp.Controls
{
    public delegate void EventEntrust(object sender, Int32 e);
    public partial class UCCustomer : UserControl
    {
        public event EventEntrust MyEvent;
        private Int32 saleID;
        private string custemerNo;
        private string storeHouse_ID;
        private string employee_ID;
        private DateTime saleDate;

        public Int32 SaleID
        {
            get { return saleID; }
            set { saleID = value; }
        }
        public string CustemerNo
        {
            get { return custemerNo; }
            set { custemerNo = value; }
        }

        public string StoreHouse_ID
        {
            get { return storeHouse_ID; }
            set { storeHouse_ID = value; }
        }

        public string Employee_ID
        {
            get { return employee_ID; }
            set { employee_ID = value; }
        }

        public DateTime SaleDate
        {
            get { return saleDate; }
            set { saleDate = value; }
        }

        public UCCustomer()
        {
            InitializeComponent();
        }


        private void UCCustomer_Load(object sender, EventArgs e)
        {
            this.lbCustomer.Text = custemerNo;
            this.lbRoom.Text = storeHouse_ID;
            this.lbOperater.Text = employee_ID;
            this.lbSaleTime.Text = saleDate.ToString("yyyy-MM-dd HH:mm:ss");
        }



        private void UCCustomer_MouseEnter(object sender, EventArgs e)
        {
            this.BackColor = Color.AliceBlue;
            this.BorderStyle = BorderStyle.Fixed3D;
        }

        private void UCCustomer_MouseLeave(object sender, EventArgs e)
        {
            this.BackColor = Color.WhiteSmoke;
            this.BorderStyle = BorderStyle.FixedSingle;
        }

        private void UCCustomer_Click(object sender, EventArgs e)
        {
            MyEvent(this, SaleID);
        }

        private void lbCustomer_Click(object sender, EventArgs e)
        {
            MyEvent(this, SaleID);
        }

        private void lbCustomer_MouseMove(object sender, MouseEventArgs e)
        {
            this.BackColor = Color.AliceBlue;
            this.BorderStyle = BorderStyle.Fixed3D;
        }

        private void lbCustomer_MouseLeave(object sender, EventArgs e)
        {
            this.BackColor = Color.WhiteSmoke;
            this.BorderStyle = BorderStyle.FixedSingle;
        }



    }
}
<file_sep>﻿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 Service.Common.Data;
using Service.Common.Log;

namespace WinApp.WinForm
{
    public partial class FormDataBackup : Form
    {
        ReturnMessage rm = new ReturnMessage();
        string BackPath;
        public ReturnMessage Rm
        {
            get { return rm; }
            set { rm = value; }
        }
        public FormDataBackup(string backPath)
        {
            InitializeComponent();
            BackPath = backPath;
        }

        private void FormDataBackup_Load(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            string strTime = string.Format("{0:yyyy-MM-dd@HH：mm：ss}", DateTime.Now);
            StringBuilder strSql = new StringBuilder();
            strSql.Append("backup database Message to disk = '" + BackPath + strTime + ".bak" + "'");
            Int32 BackupNum = 0;
            try
            {
                BackupNum = ExecuteSql.ExeComSqlForNonQuery(strSql.ToString());
                rm.Message = "备份成功！";
                rm.IsSucessed = true;
            }
            catch (Exception ex)
            {
                rm.Message = "备份失败！" + ex.Message;
                rm.IsSucessed = false;
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (rm.IsSucessed)
            {
                DialogResult = DialogResult.OK;
            }
            else
            {
                DialogResult = DialogResult.No;
            }
        }
    }
}
<file_sep>﻿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 Service.Common;
using Message.Model;

namespace WinApp.WinForm.Admin
{
    public partial class FormCreateCardType : Form
    {
        CardType ct = new CardType();
        public FormCreateCardType()
        {
            InitializeComponent();
            ControlCommon.BindDiscount(cbDiscount);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (tbxctName.Text.Trim() == "")
            {
                MessageBox.Show("请填写名称！");
                tbxctName.Focus();
                return;
            }
            ct.TypeName = tbxctName.Text;
            ct.Discount = Convert.ToDecimal(cbDiscount.SelectedValue);
            ct.Available = 1;
            if (ct.Insert().IsSucessed)
            {
                MessageBox.Show("添加成功！");
                DialogResult = DialogResult.OK;
            }
            else
            {
                MessageBox.Show("添加失败！");
                DialogResult = DialogResult.No;
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.No;
        }
    }
}
<file_sep>﻿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 Message.Model;
using Service.Common.Data;

namespace WinApp.WinForm
{
    public partial class FormMergeBill : Form
    {
        Sale SaleInfo = new Sale();
        Int32 OriginalID;
        Int32 MergerID;
        public FormMergeBill(Int32 originalID)
        {
            InitializeComponent();
            OriginalID = originalID;
            dataGridView1.AutoGenerateColumns = false;
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            if (tbxCustemerNo.Text.Trim() != "")
            {
                if (tbxCustemerNo.Text.Trim() != OriginalID.ToString())
                {
                    LoadInfo(Convert.ToInt32(tbxCustemerNo.Text));
                }
                else
                {
                    MessageBox.Show("不能和自己合并！");
                }
            }
        }

        private void LoadInfo(Int32 CustomerNo)
        {
            List<string[]> liWhere = new List<string[]>();
            liWhere.Add(new string[] { "Customer = {0}", CustomerNo.ToString() });
            liWhere.Add(new string[] { "State = {0}", "1" });
            DataTable CusDt = SaleInfo.GetDataSet("SELECT TOP 1 Sale_ID FROM Sale", liWhere);
            if (CusDt.Rows.Count > 0)
            {
                MergerID = Convert.ToInt32(CusDt.Rows[0][0]);
                SaleInfo.FindbyPK(MergerID.ToString());
                lbCanNotFind.Visible = false;
            }
            else
            {
                lbCanNotFind.Visible = true;
                return;
            }
            List<string[]> where = new List<string[]>();
            List<string[]> order = new List<string[]>();
            where.Add(new string[] { "SaleOrder_ID = {0}", MergerID.ToString() });
            order.Add(new string[] { "a.Sale_Dtl_Time", "ASC" });
            DataTable dt = SaleInfo.GetDataSet("SELECT b.Product_ID,b.Code,b.Name,convert(numeric(18,2),a.Price) AS PaidIn,convert(numeric(18,2),b.Price) AS Price,convert(numeric(18,2),a.Quantity) AS Quantity,convert(numeric(18,2),a.Price/b.Price) AS Discount, convert(numeric(18,2),a.Price*a.Quantity) AS Total,a.Employee_ID FROM Sale_Detail a LEFT JOIN Product b ON b.Product_ID = a.Product_ID", where, order);
            dataGridView1.DataSource = dt;
        }

        private void btnDetermine_Click(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count > 0)
            {
                if (MessageBox.Show("确认合并吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                {
                    Int32 result = ExecuteSql.ExeComSqlForNonQuery("UPDATE Sale_Detail SET SaleOrder_ID = " + OriginalID + " WHERE SaleOrder_ID = " + MergerID);

                    if (result == dataGridView1.Rows.Count)
                    {
                        DialogResult = DialogResult.OK;
                        List<string> strDel = new List<string>();
                        strDel.Add(SaleInfo.Sale_ID.ToString());
                        SaleInfo.Delete(strDel);
                    }
                    else
                    {
                        MessageBox.Show("合并失败！");
                        DialogResult = DialogResult.No;
                    }
                }
            }
        }

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            if (e.RowIndex >= dataGridView1.FirstDisplayedScrollingRowIndex)
            {
                using (SolidBrush b = new SolidBrush(dataGridView1.RowHeadersDefaultCellStyle.ForeColor))
                {
                    int linen = 0;
                    linen = e.RowIndex + 1;
                    string line = linen.ToString();
                    e.Graphics.DrawString(line, e.InheritedRowStyle.Font, b, e.RowBounds.Location.X, e.RowBounds.Location.Y + 5);
                    SolidBrush B = new SolidBrush(Color.Red);
                }
            }
        }

        private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            decimal TotalAmount = 0;
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                TotalAmount += Convert.ToDecimal(dataGridView1.Rows[i].Cells["Total"].Value);
            }
            lbTotal.Text = TotalAmount.ToString();
        }
    }
}
<file_sep>﻿using System;
using Service.Common.Entity;
namespace Message.Model
{
	/// <summary>
	/// ConsumptionRecords:实体类(属性说明自动提取数据库字段的描述信息)
	/// </summary>
    [TableAttribute("ConsumptionRecords")]
    public partial class ConsumptionRecords : EntityBase<ConsumptionRecords>
	{
		public ConsumptionRecords()
		{}
		#region Model
		private int _id;
		private int _cardid;
		private int _rectype;
		private decimal _amount;
		private DateTime _opetime;
		private string _tradeno;
		/// <summary>
		/// 
		/// </summary>
        [PrimaryKey("ID", IsAuto = true)]
        public int ID
		{
			set{ _id=value;}
			get{return _id;}
		}
		/// <summary>
		/// 
        /// </summary>
        [Property]
		public int CardID
		{
			set{ _cardid=value;}
			get{return _cardid;}
		}
		/// <summary>
		/// 消费类型  0：消费，1：充值
        /// </summary>
        [Property]
		public int RecType
		{
			set{ _rectype=value;}
			get{return _rectype;}
		}
		/// <summary>
		/// 
        /// </summary>
        [Property]
		public decimal Amount
		{
			set{ _amount=value;}
			get{return _amount;}
		}
		/// <summary>
		/// 
        /// </summary>
        [Property]
		public DateTime OpeTime
		{
			set{ _opetime=value;}
			get{return _opetime;}
		}
		/// <summary>
		/// 
        /// </summary>
        [Property]
		public string TradeNo
		{
			set{ _tradeno=value;}
			get{return _tradeno;}
		}
		#endregion Model

	}
}

<file_sep>﻿using System;
using Service.Common.Entity;
namespace Message.Model
{
    /// <summary>
    /// ShiftInfo:实体类(属性说明自动提取数据库字段的描述信息)
    /// </summary>
    [TableAttribute("ShiftInfo")]
    public partial class ShiftInfo : EntityBase<ShiftInfo>
	{
		public ShiftInfo()
		{}
		#region Model
		private int _id;
		private int _startid;
		private int _endid;
		private DateTime _starttime;
		private DateTime _endtime;
		private int _shiftuser;
        private DateTime _shiftTime;

        /// <summary>
        /// 
        /// </summary>
        [PrimaryKey("ID", IsAuto = true)]
		public int ID
		{
			set{ _id=value;}
			get{return _id;}
		}
		/// <summary>
		/// 
        /// </summary>
        [Property]
		public int StartID
		{
			set{ _startid=value;}
			get{return _startid;}
		}
		/// <summary>
		/// 
        /// </summary>
        [Property]
		public int EndID
		{
			set{ _endid=value;}
			get{return _endid;}
		}
		/// <summary>
		/// 
        /// </summary>
        [Property]
		public DateTime StartTime
		{
			set{ _starttime=value;}
			get{return _starttime;}
		}
		/// <summary>
		/// 
        /// </summary>
        [Property]
		public DateTime EndTime
		{
			set{ _endtime=value;}
			get{return _endtime;}
		}
		/// <summary>
		/// 
        /// </summary>
        [Property]
		public int ShiftUser
		{
			set{ _shiftuser=value;}
			get{return _shiftuser;}
		}
        /// <summary>
        /// 交班时间
        /// </summary>
        [Property]
        public DateTime ShiftTime
        {
            get { return _shiftTime; }
            set { _shiftTime = value; }
        }
		#endregion Model

	}
}

<file_sep>﻿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 Message.Model;
using System.Threading;

namespace WinApp.WinForm.Admin
{
    public partial class FormMembershipCard : Form
    {
        public FormMembershipCard()
        {
            InitializeComponent();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            ucPage1.LiWhere.Clear();
            if (tbxCardNo.Text.Trim()!="")
            {
                ucPage1.LiWhere.Add(new string[] { "CardNO = {0}", tbxCardNo.Text.Trim() });
            }
            if (tbxMemName.Text.Trim()!="")
            {
                ucPage1.LiWhere.Add(new string[] { "MemberName = {0}", tbxMemName.Text.Trim() });
            }
            if (tbxMemTel.Text.Trim() != "")
            {
                ucPage1.LiWhere.Add(new string[] { "UserTel = {0}", tbxMemTel.Text.Trim() });
            }
            dataGridView1.DataSource = ucPage1.GetDataTable();
        }

        private void FormMembershipCard_Load(object sender, EventArgs e)
        {
            ucPage1.DataSetSql = "SELECT CardType.TypeName, MemberCard.ID, MemberCard.CardNO, MemberCard.MemberName, MemberCard.UserTel, MemberCard.Balance, MemberCard.HandleTime FROM MemberCard LEFT OUTER JOIN CardType ON MemberCard.CardType = CardType.ID";
            ucPage1.LiOrder.Add(new string[] { "HandleTime", "DESC" });
            dataGridView1.DataSource = ucPage1.GetDataTable();
            ucPage1.PageEvent += new WinApp.Controls.PageEntrust(ucPage1_PageEvent);
            Employee emp = new Employee();
            emp.FindbyPK(Thread.CurrentPrincipal.Identity.Name);
            if (emp.Dept_ID != 0)
            {
                btnHandleCard.Enabled = false;
            }
        }

        void ucPage1_PageEvent()
        {
            dataGridView1.DataSource = ucPage1.GetDataTable();
        }

        private void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            FormMemCardDtl fmc = new FormMemCardDtl(Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells["ID"].Value));
            if (fmc.ShowDialog()==DialogResult.OK)
            {
                dataGridView1.DataSource = ucPage1.GetDataTable();
            }
        }

        private void btnCancle_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btnHandleCard_Click(object sender, EventArgs e)
        {
            FormCreateCard fcc = new FormCreateCard();
            if (fcc.ShowDialog() == DialogResult.OK)
            {
                ucPage1.LiWhere.Clear();
                dataGridView1.DataSource = ucPage1.GetDataTable();
            }
        }
    }
}
<file_sep>﻿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 Message.Model;
using Service.Common;
using System.Threading;

namespace WinApp.WinForm.Admin
{
    public partial class FormMemCardDtl : Form
    {
        MemberCard CardInfo = new MemberCard();
        Int32 CardID;
        public FormMemCardDtl(Int32 cardId)
        {
            InitializeComponent();
            CardID = cardId;
            GetMemberInfo();
            Employee emp = new Employee();
            emp.FindbyPK(Thread.CurrentPrincipal.Identity.Name);
            if (emp.Dept_ID != 0)
            {
                btnRecharge.Enabled = false;
                btnSave.Enabled = false;
            }
        }

        private void GetMemberInfo()
        {
            CardInfo.FindbyPK(CardID.ToString());
            tbxCardNo.Text = CardInfo.CardNO;
            tbxMemberName.Text = CardInfo.MemberName;
            ControlCommon.BindCardType(cbCardType);
            cbCardType.SelectedValue = CardInfo.CardType.ToString();
            tbxUserTel.Text = CardInfo.UserTel;
            tbxHandleTime.Text = CardInfo.HandleTime.ToString("yyyy-M-d HH:mm:ss");
            tbxLastUse.Text = CardInfo.LastUse.ToString("yyyy-M-d HH:mm:ss");
            tbxBalance.Text = CardInfo.Balance.ToString("f2");
            tbxRemarks.Text = CardInfo.Remarks;

            dataGridView1.AutoGenerateColumns = false;
            ucPage1.DataSetSql = "SELECT ID, CardID, CASE RecType WHEN 0 THEN '消费' WHEN 1 THEN '充值' END AS RecType, Amount, OpeTime, TradeNo FROM ConsumptionRecords";
            ucPage1.LiWhere.Add(new string[] { "CardID = {0}", CardID.ToString() });
            ucPage1.LiOrder.Add(new string[] { "OpeTime", "DESC" });
            dataGridView1.DataSource = ucPage1.GetDataTable();
            ucPage1.PageEvent += new WinApp.Controls.PageEntrust(ucPage1_PageEvent);
        }

        void ucPage1_PageEvent()
        {
            dataGridView1.DataSource = ucPage1.GetDataTable();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (tbxMemberName.Text.Trim() == "")
            {
                MessageBox.Show("请填写用户名！");
                tbxMemberName.Focus();
                return;
            }
            if (tbxUserTel.Text.Trim() == "")
            {
                MessageBox.Show("请填写联系电话！");
                tbxUserTel.Focus();
                return;
            }
            CardInfo.MemberName = tbxMemberName.Text;
            CardInfo.UserTel = tbxUserTel.Text;
            CardInfo.CardType = Convert.ToInt32(cbCardType.SelectedValue);
            CardInfo.Remarks = tbxRemarks.Text;
            CardInfo.Update();
            MessageBox.Show("保存成功！");
            DialogResult = DialogResult.OK;
        }

        private void btnRecharge_Click(object sender, EventArgs e)
        {
            FormRecharge fr = new FormRecharge(CardInfo.ID);
            if (fr.ShowDialog()==DialogResult.OK)
            {
                GetMemberInfo();
            }
        }

        private void btnReturn_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}
