private void btnSave_Click(object sender, EventArgs e)
        {
            var rec = new ReceiveDoc();

            var itm = new Items();
            var itemprogram = new ProgramProduct();
            string valid = ValidateFields();
            if (valid == "true")
            {
                if (
                    XtraMessageBox.Show("Are you sure you want to save this transaction?", "Confirmation",
                                        MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    try
                    {
                        for (int i = 0; i < dtRecGrid.Rows.Count; i++)
                        {
                            if (dtRecGrid.Rows[i]["Expiry Date"] != DBNull.Value)
                            {
                                if (Convert.ToDateTime(dtRecGrid.Rows[i]["Expiry Date"]) <= DateTime.Now)
                                {
                                    var dialog =
                                        XtraMessageBox.Show(
                                            "The item " + dtRecGrid.Rows[i]["Item Name"].ToString() +
                                            " has already expired.  Are you sure you want to receive it?", "Warning",
                                            MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                                    if (dialog == DialogResult.No)
                                    {
                                        return;
                                    }

                                }
                            }
                            rec.AddNew();
                            rec.StoreID = Convert.ToInt32(cboStores.EditValue);
                            rec.RefNo = txtRefNo.Text.Trim();
                            rec.Remark = txtRemark.Text;
                            rec.ReceivedBy = txtReceivedBy.Text;

                            DateTime xx = dtRecDate.Value;
                            dtRecDate.CustomFormat = "MM/dd/yyyy";
                            DateTime dtRec = new DateTime();
                            rec.Date = ConvertDate.DateConverter(dtRecDate.Text);

                            dtRec = ConvertDate.DateConverter(dtRecDate.Text);
                            dtRecDate.IsGregorianCurrentCalendar = true;

                            rec.EurDate = dtRecDate.Value;

                            dtRecDate.IsGregorianCurrentCalendar = false;

                            rec.ItemID = Convert.ToInt32(dtRecGrid.Rows[i][0]);

                            switch (VisibilitySetting.HandleUnits)
                            {
                                case 1:
                                    rec.UnitID = 0;
                                    rec.QtyPerPack = Convert.ToInt32(dtRecGrid.Rows[i]["Qty/Pack"]);
                                    break;
                                case 2:
                                    rec.UnitID = Convert.ToInt32(dtRecGrid.Rows[i]["UnitID"]);
                                    rec.QtyPerPack = 1;
                                    break;
                                case 3:
                                    rec.UnitID = Convert.ToInt32(dtRecGrid.Rows[i]["UnitID"]);
                                    rec.QtyPerPack = 1;
                                    break;
                            }
                            rec.NoOfPack = Convert.ToInt32(dtRecGrid.Rows[i]["Pack Qty"]);

                            rec.Quantity = rec.NoOfPack * rec.QtyPerPack;
                            rec.QuantityLeft = rec.Quantity;
                            if (dtRecGrid.Rows[i]["Price/Pack"] != null &&
                                dtRecGrid.Rows[i]["Price/Pack"].ToString() != "")
                            {
                                double pre = Convert.ToDouble(dtRecGrid.Rows[i]["Price/Pack"]) / rec.QtyPerPack;
                                rec.Cost = Convert.ToDouble(pre);
                            }
                            else
                            {
                                rec.Cost = 0;
                            }
                            itm.LoadByPrimaryKey(Convert.ToInt32(dtRecGrid.Rows[i]["ID"]));
                            rec.BatchNo = dtRecGrid.Rows[i][8].ToString();
                            if (dtRecGrid.Rows[i]["Expiry Date"] != DBNull.Value)
                            {
                                rec.ExpDate = Convert.ToDateTime(dtRecGrid.Rows[i]["Expiry Date"]);
                            }

                            rec.SupplierID = Convert.ToInt32(cboSupplier.EditValue);
                            rec.SubProgramID = Convert.ToInt32(cboProgram.EditValue);
                            string batch = DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() +
                                           DateTime.Now.Minute.ToString() + rec.ItemID.ToString();
                            rec.LocalBatchNo = batch;

                            rec.Out = false;
                            rec.IsApproved = false;
                            dtRecDate.Value = xx;
                            rec.Save();

                            //check if there is any data on stockoutLog about this item on this store
                            //and update its enddate to today
                            StockoutLog stockoutLog = new StockoutLog();
                            DataTable tblStockoutLog = stockoutLog.LoadByStoreAndItemId(rec.ItemID, rec.StoreID, true);
                            if (tblStockoutLog != null)
                            {
                                if (tblStockoutLog.Rows.Count > 0)
                                {
                                    stockoutLog.LoadByPrimaryKey(int.Parse(tblStockoutLog.Rows[0]["ID"].ToString()));
                                    stockoutLog.EndDate = DateTime.Today;
                                    stockoutLog.Save();
                                }
                            }

                            itemprogram.LoadByOldProgramIdAndItemId(Convert.ToInt32(dtRecGrid.Rows[i][0]),
                                                                 Convert.ToInt32(cboProgram.EditValue));
                            if (itemprogram.RowCount != 0)
                            {
                                continue;
                            }
                            else
                            {
                                itemprogram.AddNew();
                                itemprogram.ItemID = Convert.ToInt32(dtRecGrid.Rows[i][0]);
                                itemprogram.ProgramID = Convert.ToInt32(cboProgram.EditValue);
                                itemprogram.Save();
                            }
                        }
                        XtraMessageBox.Show("Transaction Successfully Saved!", "Success", MessageBoxButtons.OK,
                                            MessageBoxIcon.Information);
                        ResetFields();
                        //  mgr.CommitTransaction();

                    }
                    catch (Exception exp)
                    {
                        //mgr.RollbackTransaction();
                        BLL.User user = new User();
                        user.LoadByPrimaryKey(MainWindow.LoggedinId);
                        if (user.UserType == UserType.Constants.SYSTEM_ADMIN)
                            XtraMessageBox.Show(exp.Message);
                        else
                            XtraMessageBox.Show("Saving Error!", "Error", MessageBoxButtons.OK);
                    }
                }

            }
            else
            {
                XtraMessageBox.Show(valid, "Validation", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }
        /// <summary>
        /// Saves the item policy
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            var itm = new Items();
            var itmSup = new ItemSupplier();
            if (_itemId != 0)
                itm.LoadByPrimaryKey(_itemId);
            else
            {
                itm.AddNew();
                var prodCate = new ProductsCategory();
                prodCate.AddNew();
                prodCate.ItemId = itm.ID;
                prodCate.SubCategoryID = Convert.ToInt32(_categoryId);
                prodCate.Save();
            }
            //if (rdA.Checked || rdB.Checked || rdC.Checked)
            //    itm.ABC = ((rdA.Checked) ? 1 : (rdB.Checked) ? 2 : 3);

            //if (rdV.Checked || rdE.Checked || rdN.Checked)
            //    itm.VEN = ((rdV.Checked) ? 1 : (rdE.Checked) ? 2 : 3);

                itm.IsInHospitalList = ckExculed.Checked;
                //itm.NeedExpiryBatch = chkNeedExpiryBatch.Checked;

            string valid = ValidateFields();
            if (valid == "true")
            {
                itm.NeedExpiryBatch = chkNeedExpiryBatch.Checked;
                itm.StockCodeDACA = txtText.Text;
                itm.Cost = txtQuantityPerPack.Text;
                itm.Save();
            }

            else
            {
                XtraMessageBox.Show(valid, "Validation", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }

            //TODO: To add categories
            //Needs some modification on edit

            // this will only add the suppliers
            //do some thing on edit

            itmSup.DeleteAllSupForItem(itm.ID);
            Supplier sup = new Supplier();
            foreach (object t in lstSuppliers.CheckedItems)
            {
                sup.GetSupplierByName(t.ToString());
                itmSup.AddNew();
                itmSup.ItemID = itm.ID;
                itmSup.SupplierID = sup.ID;
                itmSup.Save();
            }

            var progItm = new ProgramProduct();
            progItm.DeleteAllProgramsForItem(_itemId);

            var prog = new Programs();
            //prog.AddNew();
            //prog.Name = cboPrograms.Text;
            //prog.Save();

            foreach (object t in lstPrograms.CheckedItems)
            {
                prog.GetProgramByName(t.ToString());
                progItm.AddNew();
                progItm.ItemID = itm.ID;
                progItm.ProgramID = prog.ID;
                progItm.Save();
            }

            var duItem = new DUsItemList();
            var dus = new ReceivingUnits();

            foreach (object t in lstDUs.CheckedItems)
            {
                dus.GetDUByName(t.ToString());
                duItem.AddNew();
                duItem.DUID = dus.ID;
                duItem.ItemID = _itemId;
                try
                {
                    duItem.Save();
                }
                catch
                {

                }
            }

            XtraMessageBox.Show("Item Detail is Saved Successfully!", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.Close();
        }
 /// <summary>
 /// When the cboPrograms changes, the program lists needs to be repopulated
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void cboPrograms_SelectedIndexChanged(object sender, EventArgs e)
 {
     lstPrograms.Items.Clear();
     Programs prog = new Programs();
     ProgramProduct progItem = new ProgramProduct();
     if (cboPrograms.SelectedValue != null)
     {
         prog.GetSubProgramsByParentId(Convert.ToInt32(cboPrograms.SelectedValue));
     }
     else
     {
         prog.GetSubPrograms();
     }
     foreach (DataRowView dv in prog.DefaultView)
     {
         bool check = false;
         check = progItem.CheckIfExists(_itemId, Convert.ToInt32(dv["ID"]));
         lstPrograms.Items.Add(dv["Name"], check);
     }
 }
        /// <summary>
        /// Populates the fields based on the supplied itemID or categoryID
        /// </summary>
        private void PopulateFields()
        {
            if (_itemId == 0)
                return;

            Items itm = new Items();

            DataTable dtItem = itm.GetItemById(_itemId);
            txtItemName.Text = dtItem.Rows[0]["ItemName"].ToString() + " - " + dtItem.Rows[0]["DosageForm"].ToString() + " - " + dtItem.Rows[0]["Strength"].ToString();
            ckExculed.Checked =itm.IsInHospitalList;
            chkNeedExpiryBatch.Checked = itm.NeedExpiryBatch;
            txtText.Text = itm.StockCodeDACA ?? string.Empty;
            txtQuantityPerPack.Text = itm.Cost ?? string.Empty;

            try
            {
                if (dtItem.Rows[0]["ABC"].ToString() == "A")
                    rdA.Checked = true;
                else if (dtItem.Rows[0]["ABC"].ToString() == "B")
                    rdB.Checked = true;
                else if (dtItem.Rows[0]["ABC"].ToString() == "C")
                    rdC.Checked = true;
            }
            catch { }

            try
            {
                if (dtItem.Rows[0]["VEN"].ToString() == "V")
                    rdV.Checked = true;
                else if (dtItem.Rows[0]["VEN"].ToString() == "E")
                    rdE.Checked = true;
                else if (dtItem.Rows[0]["VEN"].ToString() == "N")
                    rdN.Checked = true;
            }
            catch { }

            //ItemShelf itmShelf = new ItemShelf();
            //DataTable dtSlf = itmShelf.GetLocationByItem(itm.ID);
            //lstBinLocation.DataSource = dtSlf;

            var unit = new ItemUnit();
            var itemunits= unit.LoadFromSQl(_itemId);
            itemunitbindingSource.DataSource = itemunits;

            if (VisibilitySetting.HandleUnits == 2)
            {
                listBox1.Visible = true;
            }
            else if(VisibilitySetting.HandleUnits == 3)
            {
                 listBox1.Visible = true;
            }
            else if(VisibilitySetting.HandleUnits == 1)
            {
                listBox1.Hide();
            }
            Supplier sup = new Supplier();
            sup.GetActiveSuppliers();

            ItemSupplier itmSup = new ItemSupplier();
            itm.GetItemsBySupplier(_itemId);
            foreach (DataRowView dv in sup.DefaultView)
            {
                bool check = false;
                check = itmSup.CheckIfExist(_itemId, Convert.ToInt32(dv["ID"]));
                object obj = dv["CompanyName"];
                lstSuppliers.Items.Add(obj, check);
            }

            Programs prog = new Programs();
            prog.GetSubPrograms();
            ProgramProduct progItem = new ProgramProduct();
            lstPrograms.Items.Clear();
            foreach (DataRowView dv in prog.DefaultView)
            {
                bool check = false;
                check = progItem.CheckIfExists(_itemId, Convert.ToInt32(dv["ID"]));
                lstPrograms.Items.Add(dv["Name"], check);
            }

            ReceivingUnits dus = new ReceivingUnits();
            dus.GetActiveDispensaries();
            lstDUs.Items.Clear();

            DUsItemList duItem = new DUsItemList();

            foreach (DataRowView drDus in dus.DefaultView)
            {
                bool check = false;
                check = duItem.CheckIfExsits(_itemId, Convert.ToInt32(drDus["ID"]));
                lstDUs.Items.Add(drDus["Name"], check);
            }
        }
        /// <summary>
        /// After doing validation, the receive information is saved to the database.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            string valid = ValidateFields();
            if ( valid == "true")
            {
                if (XtraMessageBox.Show("Are You Sure, You want to save this Transaction?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    ReceiveDoc rec = new ReceiveDoc();
                    IssueDoc iss =new IssueDoc();
                    ProgramProduct pp = new ProgramProduct();
                    rec.LoadByPrimaryKey(_tranId);
                    iss.GetIssueByBatchAndId(rec.ItemID, rec.BatchNo, rec.ID);
                    rec.RefNo = txtRefNo.Text;
                    int previousprogid = rec.SubProgramID;
                    dtRecDate.CustomFormat = "MM/dd/yyyy";
                     string dtValid  = "";
                    try
                     {
                         rec.Date = Convert.ToDateTime(txtDate.Text);
                     }
                     catch
                     {
                         string year = "";
                         if (Convert.ToInt32(txtDate.Text.Substring(0, 2)) == 13)
                         {
                             dtValid = txtDate.Text;
                             year = dtValid.Substring(dtValid.Length - 4, 4);
                             rec.Date = Convert.ToDateTime("12/30/" + year);
                         }
                         else if (Convert.ToInt32(txtDate.Text.Substring(0, 2)) == 2)
                         {
                             dtValid = txtDate.Text;
                             year = dtValid.Substring(dtValid.Length - 4, 4);
                             rec.Date = Convert.ToDateTime("2/28/" + year);
                         }
                     }
                    if ((iss.RowCount != 0) && (iss.RecievDocID != null && iss.RecievDocID == rec.ID))
                        {
                            rec.BatchNo = txtBatchNo.Text;
                            rec.ExpDate = dtExpiryDate.Value;
                            rec.Remark = txtRemark.Text;
                            rec.ReceivedBy = txtReceivedBy.Text;
                            rec.SupplierID = Convert.ToInt32(cboSupplier.SelectedValue);
                            rec.UnitID = VisibilitySetting.HandleUnits==1 ? 0 : Convert.ToInt32(lkItemUnit.EditValue);
                            rec.StoreID = Convert.ToInt32(cboStores.SelectedValue);
                            pp.LoadByNewProgramIdAndItemId(Convert.ToInt32(rec.ItemID), Convert.ToInt32(lkPrograms.EditValue));
                            if (pp.RowCount == 1)
                            {
                                rec.SubProgramID = Convert.ToInt32(lkPrograms.EditValue);
                                pp.ProgramID = Convert.ToInt32(lkPrograms.EditValue);
                                pp.ItemID = Convert.ToInt32(rec.ItemID);
                                pp.Save();

                            }
                            else if (pp.RowCount == 0)
                            {
                                rec.SubProgramID = Convert.ToInt32(lkPrograms.EditValue);
                                pp.AddNew();
                                pp.ProgramID = rec.SubProgramID;
                                pp.ItemID = Convert.ToInt32(rec.ItemID);
                                pp.Save();
                            }
                            rec.Out = false;
                            rec.Save();
                            XtraMessageBox.Show("Transaction Succsfully Saved!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            this.Close();
                        }
                    else if (iss.RowCount == 0)
                    {
                        rec.BatchNo = txtBatchNo.Text;
                        rec.ExpDate = dtExpiryDate.Value;
                        rec.Remark = txtRemark.Text;
                        rec.ReceivedBy = txtReceivedBy.Text;
                        rec.NoOfPack = Convert.ToInt32(txtPack.Text);
                        rec.QtyPerPack = Convert.ToInt32(txtQtyPack.Text);
                        rec.Quantity = Convert.ToInt32(txtPack.Text) * Convert.ToInt32(txtQtyPack.Text);
                        rec.QuantityLeft = Convert.ToInt32(txtPack.Text) * Convert.ToInt32(txtQtyPack.Text);
                        rec.Out = false;
                        rec.StoreID = Convert.ToInt32(cboStores.SelectedValue);
                        rec.SupplierID = Convert.ToInt32(cboSupplier.SelectedValue);
                        rec.UnitID = VisibilitySetting.HandleUnits == 1 ? 0 : Convert.ToInt32(lkItemUnit.EditValue);
                        pp.LoadByNewProgramIdAndItemId(Convert.ToInt32(rec.ItemID), previousprogid);
                        if (pp.RowCount == 1)
                        {
                            rec.SubProgramID = Convert.ToInt32(lkPrograms.EditValue);
                            pp.ProgramID = Convert.ToInt32(lkPrograms.EditValue);
                            pp.ItemID = Convert.ToInt32(rec.ItemID);
                            pp.Save();

                        }
                        else if(pp.RowCount ==0)
                        {
                            rec.SubProgramID = Convert.ToInt32(lkPrograms.EditValue);
                            pp.AddNew();
                            pp.ProgramID = rec.SubProgramID;
                            pp.ItemID = Convert.ToInt32(rec.ItemID);
                            pp.Save();
                        }
                        rec.Cost = Convert.ToDouble(txtPrice.Text) / Convert.ToDouble(txtQtyPack.Text);
                        rec.Save();
                        XtraMessageBox.Show("Transaction Succsfully Saved!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.Close();
                    }

                }
            }
            else
            {
                XtraMessageBox.Show(valid, "Validation", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }