Imports System.Security.Cryptography
Imports System.Text

Public Class MD5Encryption
    Private EncStringBytes() As Byte
    Private Encoder As New UTF8Encoding
    Private MD5Hasher As New MD5CryptoServiceProvider


    'Encrptes the string in MD5 when passed as a string

    Public Function Encrypt(ByVal EncString As String) As String
        'Variable Declarations

        Dim RanGen As New Random
        Dim RanString As String = ""
        Dim MD5String As String
        Dim RanSaltLoc As String

        'Generates a Random number of under 4 digits

        While RanString.Length <= 3
            RanString = RanString & RanGen.Next(0, 9)
        End While

        'Converts the String to bytes

        EncStringBytes = Encoder.GetBytes(EncString & RanString)

        'Generates the MD5 Byte Array

        EncStringBytes = MD5Hasher.ComputeHash(EncStringBytes)

        'Affixing Salt information into the MD5 hash

        MD5String = BitConverter.ToString(EncStringBytes)
        MD5String = MD5String.Replace("-", Nothing)

        'Finds a random location in the string to sit the salt

        RanSaltLoc = CStr(RanGen.Next(4, MD5String.Length))

        'Shoves the salt in the location

        MD5String = MD5String.Insert(CInt(RanSaltLoc), RanString)

        'Adds 0 for values under 10 so we always occupy 2 charater spaces

        If CDbl(RanSaltLoc) < 10 Then
            RanSaltLoc = "0" & RanSaltLoc
        End If

        'Shoves the salt location in the string at position 3

        MD5String = MD5String.Insert(3, RanSaltLoc)

        'Returns the MD5 encrypted string to the calling object

        Return MD5String
    End Function

    'Verifies the String entered matches the MD5 Hash

    Public Function Verify(ByVal S As String, ByVal Hash As String) As Boolean
        'Variable Declarations

        Dim SaltAddress As Double
        Dim SaltID As String
        Dim NewHash As String

        'Finds the Salt Address and Removes the Salt Address from the string

        SaltAddress = CDbl(Hash.Substring(3, 2))
        Hash = Hash.Remove(3, 2)

        'Finds the SaltID and removes it from the string

        SaltID = Hash.Substring(CInt(SaltAddress), 4)
        Hash = Hash.Remove(CInt(SaltAddress), 4)

        'Converts the string passed to us to Bytes

        EncStringBytes = Encoder.GetBytes(S & SaltID)

        'Encryptes the string passed to us with the salt

        EncStringBytes = MD5Hasher.ComputeHash(EncStringBytes)

        'Converts the Hash to a string

        NewHash = BitConverter.ToString(EncStringBytes)
        NewHash = NewHash.Replace("-", Nothing)

        'Tests the new has against the one passed to us
        Dim val As Boolean
        If NewHash = Hash Then
            val = True
        ElseIf NewHash <> Hash Then
            val = False
        End If
        Return val
    End Function
End Class


 Dim md5 As New MD5Encryption()
Password = md5.Encrypt(txtPassword.Text.Trim())

md5.Verify(txtPassword.Text, password)
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
public class Purchases : IControlEvent
{
public long PurchaseOrderID = 0;
public DataTable dt;
public DataSet ds = new DataSet();
private DataView mView;
Theme _theme;
public event ChangedEventHandler Changed;
public delegate void ChangedEventHandler();
private long EnteredBy;
ComboBox cmbProductCode;
private string pCode;
public DataRowView dv;
public int ProductID = 0;
public List<long> ProductIDs = new List<long>();
DataGridViewComboBoxColumn combocolum = new DataGridViewComboBoxColumn();
DataGridViewComboBoxColumn namecombocolum = new DataGridViewComboBoxColumn();

int PurchaseItemID = 0;
public enum CBO_MODE
{
NORMAL = 0,
EDITABLE = 1,
EDITABLE_WITH_NOTIFYCURRENTCELLDIRTY = 2
}

const bool ALLOW_ADDS = true;

private CBO_MODE MODE = CBO_MODE.EDITABLE_WITH_NOTIFYCURRENTCELLDIRTY;
public bool Notify(object obj)
{
try {
PurchaseOrderID = Convert.ToInt32(obj);
FillDetails(PurchaseOrderID);
FillGrid(PurchaseOrderID);
btnDelete.Enabled = true;
} catch (Exception ex) {
Utils.LogHandler.HandleError(ex);
return false;
}
return true;
}

private void FillDetails(long PurchaseOrderID)
{
POSCLayer.Purchaseorders c = new POSCLayer.Purchaseorders();
c = POSBLayer.Purchaseorders.GetValue(PurchaseOrderID);
if (c != null) {
dtpPurchaseDate.Value = c.PurchaseDate;
txtInvoiceNumber.Text = c.InvoiceNumber;
txtOrderDetail.Text = c.OrderDetail;
txtRemarks.Text = c.Remarks;
txtTotalAmount.Text = c.TotalAmount.ToString();
EnteredBy = c.EnteredBy;
btnDelete.Enabled = true;
}
}

public void FillGrid(long PurchaseOrderID)
{
DataTable dtgrid = POSBLayer.Purchaseitems.GetDataAll(PurchaseOrderID);
int j = 0;
dgvPurchaseItems.Rows.Clear();
if (dtgrid.Rows.Count > 0) {
for (j = 0; j <= dtgrid.Rows.Count - 1; j++) {
dgvPurchaseItems.Rows.Add();
//dgvPurchaseItems("Name", j).Value = dtgrid.Rows(j)("Name").ToString()
dgvPurchaseItems("Quantity", j).Value = dtgrid.Rows[j]["Quantity"].ToString();
dgvPurchaseItems("Damaged", j).Value = dtgrid.Rows[j]["Damaged"].ToString();
dgvPurchaseItems("Expired", j).Value = dtgrid.Rows[j]["Expired"].ToString();
dgvPurchaseItems("PurchaseRate", j).Value = dtgrid.Rows[j]["PurchaseRate"].ToString();
dgvPurchaseItems("SellingRate", j).Value = dtgrid.Rows[j]["SellingRate"].ToString();
dgvPurchaseItems("Current", j).Value = dtgrid.Rows[j]["Current"].ToString();
dgvPurchaseItems("Loose", j).Value = dtgrid.Rows[j]["Loose"].ToString();
dgvPurchaseItems("PurchaseItemID", j).Value = dtgrid.Rows[j]["PurchaseItemID"].ToString();
dgvPurchaseItems("ProductID", j).Value = dtgrid.Rows[j]["ProductID"].ToString();

//Dim combo As DataGridViewComboBoxCell = TryCast(dgvPurchaseItems(0, j), DataGridViewComboBoxCell)
//Dim dt As DataTable = POSBLayer.Products.GetDataAll()
//combo.DataSource = dt
dgvPurchaseItems.Rows(j).Cells(combocolum.Name).Value = dtgrid.Rows[j]["pcode"].ToString();
dgvPurchaseItems.Rows(j).Cells(namecombocolum.Name).Value = dtgrid.Rows[j]["Name"].ToString();
ProductIDs.Add(Convert.ToInt64(dtgrid.Rows[j]["ProductID"].ToString()));
}
} else {
dgvPurchaseItems.Rows.Clear();
}
}

private void btnSave_Click(System.Object sender, System.EventArgs e)
{
try {

if (!string.IsNullOrEmpty(txtInvoiceNumber.Text) & !string.IsNullOrEmpty(txtOrderDetail.Text) & !string.IsNullOrEmpty(txtTotalAmount.Text)) {
POSCLayer.Purchaseorders data = new POSCLayer.Purchaseorders();
data.PurchaseOrderID = PurchaseOrderID;
data.PurchaseDate = dtpPurchaseDate.Value;
data.OrderDetail = txtOrderDetail.Text;
data.Remarks = txtRemarks.Text;
data.InvoiceNumber = txtInvoiceNumber.Text;
data.TotalAmount = Convert.ToDecimal(txtTotalAmount.Text);
if (PurchaseOrderID == 0) {
data.EnteredBy = Config.User.UserID;
EnteredBy = Config.User.UserID;
} else {
data.EnteredBy = EnteredBy;
}
data.ModifiedBy = Config.User.UserID;

long result = POSBLayer.Purchaseorders.Save(data);
PurchaseOrderID = result;


btnNew.Enabled = true;
btnDelete.Enabled = false;

POSCLayer.Purchaseitems data1 = new POSCLayer.Purchaseitems();
int i = 0;


foreach (DataGridViewRow row in dgvPurchaseItems.Rows) {

if (row.Cells("PurchaseItemID").Value != null & row.Cells("ProductID").Value != null & row.Cells("Quantity").Value != null & row.Cells("Damaged").Value != null & row.Cells("Expired").Value != null & row.Cells("PurchaseRate").Value != null & row.Cells("SellingRate").Value != null & row.Cells("Current").Value != null) {
if (row.Cells("PurchaseItemID").Value != null) {
int.TryParse(row.Cells("PurchaseItemID").Value.ToString(), out PurchaseItemID);
}

if (row.Cells("ProductID").Value != null) {
int.TryParse(row.Cells("ProductID").Value.ToString(), out ProductID);
}


data1.PurchaseOrderID = PurchaseOrderID;
data1.ProductID = ProductID;

DataTable dtItems = POSBLayer.Purchaseitems.Get_PurchaseItems_ProductID(PurchaseOrderID, ProductID);

if (dtItems.Rows.Count > 0) {
if (PurchaseItemID == 0) {
data1.PurchaseItemID = POSBLayer.Purchaseitems.Get_PurchaseItemsID(PurchaseOrderID, ProductID);
data1.Quantity = decimal.Parse(row.Cells("Quantity").Value.ToString()) + decimal.Parse(dtItems.Rows[0]["Quantity"].ToString());
data1.DamagedQuantity = decimal.Parse(row.Cells("Damaged").Value.ToString()) + decimal.Parse(dtItems.Rows[0]["DamagedQuantity"].ToString());
data1.ExpiredQuantity = decimal.Parse(row.Cells("Expired").Value.ToString()) + decimal.Parse(dtItems.Rows[0]["ExpiredQuantity"].ToString());
data1.PurchasePrice = decimal.Parse(row.Cells("PurchaseRate").Value.ToString()) + decimal.Parse(dtItems.Rows[0]["PurchasePrice"].ToString());
data1.SellingPrice = decimal.Parse(row.Cells("SellingRate").Value.ToString()) + decimal.Parse(dtItems.Rows[0]["SellingPrice"].ToString());
data1.CurrentQuantity = decimal.Parse(row.Cells("Current").Value.ToString()) + decimal.Parse(dtItems.Rows[0]["CurrentQuantity"].ToString());
data1.CurrentLooseVolume = 0;
data1.LooseQuantity = 0;
} else {
data1.PurchaseItemID = PurchaseItemID;
data1.Quantity = decimal.Parse(row.Cells("Quantity").Value.ToString());
data1.DamagedQuantity = decimal.Parse(row.Cells("Damaged").Value.ToString());
data1.ExpiredQuantity = decimal.Parse(row.Cells("Expired").Value.ToString());
data1.PurchasePrice = decimal.Parse(row.Cells("PurchaseRate").Value.ToString());
data1.SellingPrice = decimal.Parse(row.Cells("SellingRate").Value.ToString());
data1.CurrentQuantity = decimal.Parse(row.Cells("Current").Value.ToString());
data1.CurrentLooseVolume = 0;
data1.LooseQuantity = 0;
}
} else {
data1.PurchaseItemID = PurchaseItemID;
data1.Quantity = decimal.Parse(row.Cells("Quantity").Value.ToString());
data1.DamagedQuantity = decimal.Parse(row.Cells("Damaged").Value.ToString());
data1.ExpiredQuantity = decimal.Parse(row.Cells("Expired").Value.ToString());
data1.PurchasePrice = decimal.Parse(row.Cells("PurchaseRate").Value.ToString());
data1.SellingPrice = decimal.Parse(row.Cells("SellingRate").Value.ToString());
data1.CurrentQuantity = decimal.Parse(row.Cells("Current").Value.ToString());
data1.CurrentLooseVolume = 0;
data1.LooseQuantity = 0;
}


result = POSBLayer.Purchaseitems.Save(data1);
i = i + 1;
}
}

if (Changed != null) {
Changed();
}

MessageBox.Show("Saved successfully.", "POS", MessageBoxButtons.OK, MessageBoxIcon.Information);
} else {
MessageBox.Show("Please enter required fields", "POS", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
} catch (Exception ex) {
Utils.LogHandler.HandleError(ex);
}
}

private void Clear()
{
PurchaseOrderID = 0;
dtpPurchaseDate.Value = Convert.ToDateTime(DateAndTime.Now.ToString("dd-MM-yyyy"));
txtOrderDetail.Text = "";
txtRemarks.Text = "";
txtInvoiceNumber.Text = "";
txtTotalAmount.Text = "";
btnDelete.Enabled = false;
}

private void btnNew_Click(System.Object sender, System.EventArgs e)
{
try {
Clear();
dgvPurchaseItems.Rows.Clear();
} catch (Exception ex) {
Utils.LogHandler.HandleError(ex);
}
}

private void btnDelete_Click(System.Object sender, System.EventArgs e)
{
try {
int checkPurchaseOrderID = 0;
checkPurchaseOrderID = POSBLayer.Purchaseorders.checkPurchaseOrderID(Convert.ToInt32(PurchaseOrderID));
if (checkPurchaseOrderID == 0) {
DialogResult msgResult = DialogResult.No;
msgResult = MessageBox.Show("Are you sure you want to remove the record ?", Config.MsgTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (msgResult == DialogResult.Yes) {
if (!string.IsNullOrEmpty(txtInvoiceNumber.Text) & !string.IsNullOrEmpty(txtOrderDetail.Text) & !string.IsNullOrEmpty(txtTotalAmount.Text)) {
int result = Convert.ToInt32(POSBLayer.Purchaseorders.Delete(PurchaseOrderID));

Clear();
if (Changed != null) {
Changed();
}
} else {
MessageBox.Show("Please enter required fields", Config.MsgTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
} else {
dtpPurchaseDate.Focus();
}
} else {
MessageBox.Show("Cannot delete, this Purchase Order is already assigned to a Purchase Items.", Config.MsgTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
} catch (Exception ex) {
Utils.LogHandler.HandleError(ex);
}
}

private void Purchases_Load(object sender, System.EventArgs e)
{
try {


DataTable dt = POSBLayer.Products.GetDataAll();

combocolum.DefaultCellStyle.Tag = "editable";
//  this is the enhance to control if editable or not
combocolum.HeaderText = "Code";
combocolum.DataPropertyName = "ProductID";
combocolum.DataSource = dt;
combocolum.DisplayMember = "pcode";
combocolum.ValueMember = "ProductID";
combocolum.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
combocolum.Name = "Product";
combocolum.ValueType = typeof(System.String);
combocolum.Width = 200;
dgvPurchaseItems.Columns.Add(combocolum);

//Dim Namecolum As New DataGridViewTextBoxColumn
//Namecolum.HeaderText = "Name"
//Namecolum.Name = "Name"
//Namecolum.ValueType = GetType(System.String)
//Namecolum.Width = 170
//Namecolum.ReadOnly = True
//dgvPurchaseItems.Columns.Add(Namecolum)
namecombocolum.DefaultCellStyle.Tag = "editable";
//  this is the enhance to control if editable or not
namecombocolum.HeaderText = "Name";
namecombocolum.DataPropertyName = "ProductID";
namecombocolum.DataSource = dt;
namecombocolum.DisplayMember = "NAME";
namecombocolum.ValueMember = "ProductID";
namecombocolum.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
namecombocolum.Name = "Name";
namecombocolum.ValueType = typeof(System.String);
namecombocolum.Width = 170;
dgvPurchaseItems.Columns.Add(namecombocolum);

DataGridViewTextBoxColumn Quantitycolum = new DataGridViewTextBoxColumn();
Quantitycolum.HeaderText = "Quantity";
Quantitycolum.Name = "Quantity";
Quantitycolum.ValueType = typeof(System.Decimal);
Quantitycolum.Width = 70;
dgvPurchaseItems.Columns.Add(Quantitycolum);

DataGridViewTextBoxColumn Damagedcolum = new DataGridViewTextBoxColumn();
Damagedcolum.HeaderText = "Damaged";
Damagedcolum.Name = "Damaged";
Damagedcolum.ValueType = typeof(System.Decimal);
Damagedcolum.Width = 70;
dgvPurchaseItems.Columns.Add(Damagedcolum);

DataGridViewTextBoxColumn Expiredcolum = new DataGridViewTextBoxColumn();
Expiredcolum.HeaderText = "Expired";
Expiredcolum.Name = "Expired";
Expiredcolum.ValueType = typeof(System.Decimal);
Expiredcolum.Width = 70;
dgvPurchaseItems.Columns.Add(Expiredcolum);

DataGridViewTextBoxColumn PurchaseRatecolum = new DataGridViewTextBoxColumn();
PurchaseRatecolum.HeaderText = "Purchase Rate";
PurchaseRatecolum.Name = "PurchaseRate";
PurchaseRatecolum.ValueType = typeof(System.Decimal);
PurchaseRatecolum.Width = 110;
dgvPurchaseItems.Columns.Add(PurchaseRatecolum);

DataGridViewTextBoxColumn SellingRatecolum = new DataGridViewTextBoxColumn();
SellingRatecolum.HeaderText = "Selling Rate";
SellingRatecolum.Name = "SellingRate";
SellingRatecolum.ValueType = typeof(System.Decimal);
SellingRatecolum.Width = 100;
dgvPurchaseItems.Columns.Add(SellingRatecolum);

DataGridViewTextBoxColumn Currentcolum = new DataGridViewTextBoxColumn();
Currentcolum.HeaderText = "Current";
Currentcolum.Name = "Current";
Currentcolum.ValueType = typeof(System.Decimal);
Currentcolum.ReadOnly = true;
Currentcolum.Width = 70;
dgvPurchaseItems.Columns.Add(Currentcolum);

DataGridViewTextBoxColumn Loosecolum = new DataGridViewTextBoxColumn();
Loosecolum.HeaderText = "Loose";
Loosecolum.Name = "Loose";
Loosecolum.ValueType = typeof(System.Decimal);
Loosecolum.ReadOnly = true;
Loosecolum.Width = 70;
dgvPurchaseItems.Columns.Add(Loosecolum);

DataGridViewTextBoxColumn PurchaseItemIDcolum = new DataGridViewTextBoxColumn();
PurchaseItemIDcolum.HeaderText = "PurchaseItemID";
PurchaseItemIDcolum.Name = "PurchaseItemID";
PurchaseItemIDcolum.ValueType = typeof(System.Decimal);
PurchaseItemIDcolum.Width = 70;
dgvPurchaseItems.Columns.Add(PurchaseItemIDcolum);

DataGridViewTextBoxColumn ProductIDcolum = new DataGridViewTextBoxColumn();
ProductIDcolum.HeaderText = "ProductID";
ProductIDcolum.Name = "ProductID";
ProductIDcolum.ValueType = typeof(System.Decimal);
ProductIDcolum.Width = 70;
dgvPurchaseItems.Columns.Add(ProductIDcolum);

DataGridViewLinkColumn Deletecolum = new DataGridViewLinkColumn();
Deletecolum.HeaderText = "Delete";
Deletecolum.Name = "Delete";
Deletecolum.Width = 70;
Deletecolum.Text = "Delete";
Deletecolum.UseColumnTextForLinkValue = true;
dgvPurchaseItems.Columns.Add(Deletecolum);

//Dim Savecolum As New DataGridViewLinkColumn
//Savecolum.HeaderText = "Save"
//Savecolum.Name = "Save"
//Savecolum.Width = 70
//Savecolum.Text = "Save"
//Savecolum.UseColumnTextForLinkValue = True
//dgvPurchaseItems.Columns.Add(Savecolum)


dgvPurchaseItems.RowHeadersVisible = false;
dgvPurchaseItems.BackgroundColor = Color.White;
dgvPurchaseItems.Columns("PurchaseItemID").Visible = false;
dgvPurchaseItems.Columns("ProductID").Visible = false;
//Theme.SetGridViewStyle(dgvPurchaseItems)
Theme.SetControlTheme(this);
} catch (Exception ex) {
Utils.LogHandler.HandleError(ex);
}
}

private void dgvPurchaseItems_EditingControlShowing(System.Object sender, System.Windows.Forms.DataGridViewEditingControlShowingEventArgs e)
{
try {
// Here you control if combobox will be editable or not
if (object.ReferenceEquals(e.CellStyle.Tag, "editable")) {
DataGridView dgvPurchaseItems = (DataGridView)sender;
if (((e.Control) is ComboBox)) {
ComboBox cb = (ComboBox)e.Control;
if (((cb != null))) {
cb.DropDownStyle = ComboBoxStyle.DropDown;
cb.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
cb.AutoCompleteSource = AutoCompleteSource.ListItems;
cb.SelectionChangeCommitted += cmbProductCodeOnSelectionChangeCommitted;
cb.LostFocus += cmbProductCode_LostFocus;
cb.Leave += cmbProductCode_Leave;

if ((MODE == CBO_MODE.EDITABLE_WITH_NOTIFYCURRENTCELLDIRTY)) {
// Added thanks to Ying Liu, Microsoft Support
dgvPurchaseItems.NotifyCurrentCellDirty(true);
}
}
}

}
} catch (Exception ex) {
Utils.LogHandler.HandleError(ex);
}
}

private void cmbProductCodeOnSelectionChangeCommitted(object sender, EventArgs e)
{
DataGridViewComboBoxEditingControl comboBox = sender as DataGridViewComboBoxEditingControl;
if (sender == null) {
return;
}
if (comboBox.SelectedItem == null) {
return;
}
if (object.ReferenceEquals(this.dgvPurchaseItems.CurrentCell.Value, comboBox.SelectedItem)) {
return;
}

this.dgvPurchaseItems.CurrentCell.Value = comboBox.SelectedItem;
dv = (DataRowView)comboBox.SelectedItem;
pCode = Convert.ToString(dv["pcode"]);
ProductIDs.Add(Convert.ToInt64(dv["ProductID"]));
ProductID = Convert.ToInt32(dv["ProductID"]);

}

private void cmbProductCode_LostFocus(object sender, EventArgs e)
{
DataGridViewComboBoxEditingControl comboBox = sender as DataGridViewComboBoxEditingControl;
if (sender == null) {
return;
}
if (comboBox.SelectedItem == null) {
return;
}
if (object.ReferenceEquals(this.dgvPurchaseItems.CurrentCell.Value, comboBox.SelectedItem)) {
return;
}

this.dgvPurchaseItems.CurrentCell.Value = comboBox.SelectedItem;
dv = (DataRowView)comboBox.SelectedItem;
pCode = Convert.ToString(dv["pcode"]);
ProductIDs.Add(Convert.ToInt64(dv["ProductID"]));
ProductID = Convert.ToInt32(dv["ProductID"]);


}

private void cmbProductCode_Leave(object sender, EventArgs e)
{
DataGridViewComboBoxEditingControl comboBox = sender as DataGridViewComboBoxEditingControl;
if (sender == null) {
return;
}
if (comboBox.SelectedItem == null) {
return;
}
if (object.ReferenceEquals(this.dgvPurchaseItems.CurrentCell.Value, comboBox.SelectedItem)) {
return;
}

this.dgvPurchaseItems.CurrentCell.Value = comboBox.SelectedItem;
dv = (DataRowView)comboBox.SelectedItem;
pCode = Convert.ToString(dv["pcode"]);
ProductIDs.Add(Convert.ToInt64(dv["ProductID"]));
ProductID = Convert.ToInt32(dv["ProductID"]);


}

private void dgvPurchaseItems_CellEndEdit(System.Object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
{

try {
int j = e.RowIndex;
decimal q = default(decimal);
decimal d = default(decimal);
decimal r = default(decimal);
decimal c = default(decimal);

decimal.TryParse(Convert.ToString(dgvPurchaseItems.Rows(j).Cells("Quantity").Value), out q);
decimal.TryParse(Convert.ToString(dgvPurchaseItems.Rows(j).Cells("Damaged").Value), out d);
decimal.TryParse(Convert.ToString(dgvPurchaseItems.Rows(j).Cells("Expired").Value), out r);

if (q < d + r) {
MessageBox.Show("Enter Quantity greater than Damaged and Expired.", "POS", MessageBoxButtons.OK, MessageBoxIcon.Information);
} else {
c = q - (d + r);
}




dgvPurchaseItems.Rows(j).Cells("Current").Value = c.ToString();
dgvPurchaseItems.Rows(j).Cells("Loose").Value = 0;

if (ProductID != 0) {
dgvPurchaseItems.Rows(j).Cells("ProductID").Value = ProductID;
dgvPurchaseItems.Rows(j).Cells("Name").Value = POSBLayer.Purchaseitems.GetProductName(ProductID);
dgvPurchaseItems.Rows(j).Cells("Product").Value = POSBLayer.Purchaseitems.GetProductCode(ProductID);
} else {
Name = Convert.ToString(dgvPurchaseItems.Rows(j).Cells("Name").Value);
pCode = Convert.ToString(dgvPurchaseItems.Rows(j).Cells("Product").Value);
dgvPurchaseItems.Rows(j).Cells("Name").Value = Name;
dgvPurchaseItems.Rows(j).Cells("Product").Value = pCode;
}

if (dgvPurchaseItems.Rows(j).Cells("PurchaseItemID").Value == null) {
dgvPurchaseItems.Rows(j).Cells("PurchaseItemID").Value = PurchaseItemID;
}


//Dim data1 As New POSCLayer.Purchaseitems

//data1.PurchaseItemID = CLng(dgvPurchaseItems.Rows(j).Cells(8).Value.ToString())
//data1.PurchaseOrderID = PurchaseOrderID
//data1.ProductID = CLng(dgvPurchaseItems.Rows(j).Cells(9).Value.ToString())
//data1.Quantity = Decimal.Parse(dgvPurchaseItems.Rows(j).Cells("Quantity").Value.ToString())
//data1.DamagedQuantity = Decimal.Parse(dgvPurchaseItems.Rows(j).Cells("Damaged").Value.ToString())
//data1.ExpiredQuantity = Decimal.Parse(dgvPurchaseItems.Rows(j).Cells("Expired").Value.ToString())
//data1.PurchasePrice = Decimal.Parse(dgvPurchaseItems.Rows(j).Cells("PurchaseRate").Value.ToString())
//data1.SellingPrice = Decimal.Parse(dgvPurchaseItems.Rows(j).Cells("SellingRate").Value.ToString())
//data1.CurrentQuantity = Decimal.Parse(dgvPurchaseItems.Rows(j).Cells("Current").Value.ToString())
//data1.CurrentLooseVolume = 0
//data1.LooseQuantity = Decimal.Parse(dgvPurchaseItems.Rows(j).Cells("Loose").Value.ToString())
//Dim result = POSBLayer.Purchaseitems.Save(data1)
//MessageBox.Show("Saved successfully.",
//                                   "POS",
//                                   MessageBoxButtons.OK,
//                                   MessageBoxIcon.Information)
//FillGrid(PurchaseOrderID)

} catch (Exception ex) {
Utils.LogHandler.HandleError(ex);
}
}

private void dgvPurchaseItems_CellLeave(System.Object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
{
try {
//If Not cmbProductCode Is Nothing Then
//    pCode = cmbProductCode.Text
//    Dim dt As DataTable = POSBLayer.Products.GetDataAll()
//    cmbProductCode.DataSource = dt
//    cmbProductCode.DisplayMember = "Code"
//    cmbProductCode.ValueMember = "ProductID"
//    cmbProductCode.SelectedIndex = cmbProductCode.FindStringExact(pCode)
//    cmbProductCode.Text = pCode
//    cmbProductCode.DroppedDown = False


//End If
} catch (Exception ex) {
Utils.LogHandler.HandleError(ex);
}
}

private void dgvPurchaseItems_CellValidating(System.Object sender, System.Windows.Forms.DataGridViewCellValidatingEventArgs e)
{
try {
DataGridView dgvPurchaseItems = (DataGridView)sender;
if ((dgvPurchaseItems.Columns(e.ColumnIndex) is DataGridViewComboBoxColumn)) {
DataGridViewComboBoxColumn comboBoxColumn = (DataGridViewComboBoxColumn)dgvPurchaseItems.Columns(e.ColumnIndex);
if ((!comboBoxColumn.Items.Contains(e.FormattedValue))) {
if ((ALLOW_ADDS)) {
//Beep() ' Audio confirmation that the item has been added (optional)
//comboBoxColumn.Items.Add(e.FormattedValue)
} else {
// How do we cancel?
e.Cancel = true;
}
}
} else {

}

} catch (Exception ex) {
Utils.LogHandler.HandleError(ex);
}
}

private void dgvPurchaseItems_DataError(System.Object sender, System.Windows.Forms.DataGridViewDataErrorEventArgs e)
{
try {
if (e.Exception != null) {
// checking Integer numbers

if (dgvPurchaseItems.Columns(e.ColumnIndex).ValueType.ToString() == "System.Int32") {
MessageBox.Show("Enter only Integer values ");
// checking decimal values 
} else if (dgvPurchaseItems.Columns(e.ColumnIndex).ValueType.ToString() == "System.Decimal") {
MessageBox.Show("Enter only numbers");
} else if (dgvPurchaseItems.Columns(e.ColumnIndex).ValueType.ToString() == "System.String") {
//MessageBox.Show("Enter only numbers")
} else {
MessageBox.Show("Enter correct format data. Different format data will not accept");

}
}
} catch (Exception ex) {
Utils.LogHandler.HandleError(ex);
}
}

private void dgvPurchaseItems_CellContentClick(System.Object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
{
try {
if (e.ColumnIndex == 11) {
int j = e.RowIndex;
POSCLayer.Purchaseitems data1 = new POSCLayer.Purchaseitems();

data1.PurchaseItemID = Convert.ToInt64(dgvPurchaseItems.Rows(j).Cells("PurchaseItemID").Value.ToString());
dynamic pid = POSBLayer.Purchaseitems.GetPurchaseItemID(data1.PurchaseItemID);
if (pid > 0) {
MessageBox.Show("Cannot delete.", "POS", MessageBoxButtons.OK, MessageBoxIcon.Information);
} else {
dynamic result = POSBLayer.Purchaseitems.Delete(data1.PurchaseItemID);
MessageBox.Show("Deleted successfully.", "POS", MessageBoxButtons.OK, MessageBoxIcon.Information);
FillGrid(PurchaseOrderID);
}

} else {
//If e.ColumnIndex = 11 Then
//    If PurchaseOrderID <> 0 Then

//        Dim j As Integer = e.RowIndex
//        Dim data1 As New POSCLayer.Purchaseitems

//        data1.PurchaseItemID = CLng(dgvPurchaseItems.Rows(j).Cells(8).Value.ToString())
//        data1.PurchaseOrderID = PurchaseOrderID
//        data1.ProductID = CLng(dgvPurchaseItems.Rows(j).Cells(9).Value.ToString())
//        data1.Quantity = Decimal.Parse(dgvPurchaseItems.Rows(j).Cells("Quantity").Value.ToString())
//        data1.DamagedQuantity = Decimal.Parse(dgvPurchaseItems.Rows(j).Cells("Damaged").Value.ToString())
//        data1.ExpiredQuantity = Decimal.Parse(dgvPurchaseItems.Rows(j).Cells("Expired").Value.ToString())
//        data1.PurchasePrice = Decimal.Parse(dgvPurchaseItems.Rows(j).Cells("PurchaseRate").Value.ToString())
//        data1.SellingPrice = Decimal.Parse(dgvPurchaseItems.Rows(j).Cells("SellingRate").Value.ToString())
//        data1.CurrentQuantity = Decimal.Parse(dgvPurchaseItems.Rows(j).Cells("Current").Value.ToString())
//        data1.CurrentLooseVolume = 0
//        data1.LooseQuantity = Decimal.Parse(dgvPurchaseItems.Rows(j).Cells("Loose").Value.ToString())
//        Dim result = POSBLayer.Purchaseitems.Save(data1)
//        MessageBox.Show("Saved successfully.",
//                                           "POS",
//                                           MessageBoxButtons.OK,
//                                           MessageBoxIcon.Information)
//        FillGrid(PurchaseOrderID)

//    End If
}
} catch (Exception ex) {
Utils.LogHandler.HandleError(ex);
}
}
public Purchases()
{
Load += Purchases_Load;
}

}