protected void FillGrid()
    {
        if (!IsValidFormID())
        {
            HideTableAndSetErrorMessage("", "Invalid URL Parameters");
            return;
        }

        Organisation org = OrganisationDB.GetByID(GetFormID());

        if (org == null)
        {
            HideTableAndSetErrorMessage("", "Invalid URL Parameters");
            return;
        }

        lblHeading.Text             = Page.Title = "Manage Registrations For :  " + org.Name;
        this.lnkThisOrg.NavigateUrl = "~/OrganisationDetailV2.aspx?type=view&id=" + GetFormID().ToString();
        this.lnkThisOrg.Text        = "Back to details for " + org.Name;



        string searchSurname = "";

        if (Request.QueryString["surname_search"] != null && Request.QueryString["surname_search"].Length > 0)
        {
            searchSurname         = Request.QueryString["surname_search"];
            txtSearchSurname.Text = Request.QueryString["surname_search"];
        }
        bool searchSurnameOnlyStartsWith = true;

        if (Request.QueryString["surname_starts_with"] != null && Request.QueryString["surname_starts_with"].Length > 0)
        {
            searchSurnameOnlyStartsWith           = Request.QueryString["surname_starts_with"] == "0" ? false : true;
            chkSurnameSearchOnlyStartWith.Checked = searchSurnameOnlyStartsWith;
        }
        else
        {
            chkSurnameSearchOnlyStartWith.Checked = searchSurnameOnlyStartsWith;
        }


        DataTable dt = RegisterPatientDB.GetDataTable_PatientsOf(GetFormViewOnlyLast(), org.OrganisationID, false, false, false, false, searchSurname, searchSurnameOnlyStartsWith);


        int[] ptIDs = new int[dt.Rows.Count];
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            ptIDs[i] = Convert.ToInt32(dt.Rows[i]["patient_id"]);
        }


        // get last and next booking dates

        Hashtable lastBookingDates = BookingDB.GetLastBookingDates(ptIDs, org.OrganisationID);
        Hashtable nextBookingDates = BookingDB.GetNextBookingDates(ptIDs, org.OrganisationID);

        dt.Columns.Add("last_booking_date", typeof(DateTime));
        dt.Columns.Add("next_booking_date", typeof(DateTime));
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            dt.Rows[i]["last_booking_date"] = lastBookingDates[Convert.ToInt32(dt.Rows[i]["patient_id"])] == null ? (object)DBNull.Value : (DateTime)lastBookingDates[Convert.ToInt32(dt.Rows[i]["patient_id"])];
            dt.Rows[i]["next_booking_date"] = nextBookingDates[Convert.ToInt32(dt.Rows[i]["patient_id"])] == null ? (object)DBNull.Value : (DateTime)nextBookingDates[Convert.ToInt32(dt.Rows[i]["patient_id"])];
        }



        // get epc info

        Hashtable mostRecentRecallHashByPatientID = LetterPrintHistoryDB.GetMostRecentRecallHashByPatients(ptIDs);

        Hashtable patientHealthCardCache        = PatientsHealthCardsCacheDB.GetBullkActive(ptIDs);
        Hashtable epcRemainingCache             = GetEPCRemainingCache(patientHealthCardCache);
        Hashtable patientsMedicareCountCache    = PatientsMedicareCardCountThisYearCacheDB.GetBullk(ptIDs, DateTime.Today.Year);
        Hashtable patientsEPCRemainingCache     = PatientsEPCRemainingCacheDB.GetBullk(ptIDs, DateTime.Today.AddYears(-1));
        int       MedicareMaxNbrServicesPerYear = Convert.ToInt32(SystemVariableDB.GetByDescr("MedicareMaxNbrServicesPerYear").Value);


        dt.Columns.Add("epc_expire_date", typeof(DateTime));
        dt.Columns.Add("has_valid_epc", typeof(Boolean));
        dt.Columns.Add("epc_count_remaining", typeof(Int32));

        dt.Columns.Add("most_recent_recall_sent", typeof(DateTime));
        for (int i = dt.Rows.Count - 1; i >= 0; i--)
        {
            int patientID = Convert.ToInt32(dt.Rows[i]["patient_id"]);

            HealthCard hc     = GetHealthCardFromCache(patientHealthCardCache, patientID);
            bool       hasEPC = hc != null && hc.DateReferralSigned != DateTime.MinValue;
            HealthCardEPCRemaining[] epcsRemaining = !hasEPC ? new HealthCardEPCRemaining[] { } : GetEPCRemainingFromCache(epcRemainingCache, hc);
            int totalServicesAllowedLeft           = !hasEPC ? 0 : (MedicareMaxNbrServicesPerYear - (int)patientsMedicareCountCache[patientID]);

            int totalEpcsRemaining = 0;
            for (int j = 0; j < epcsRemaining.Length; j++)
            {
                totalEpcsRemaining += epcsRemaining[j].NumServicesRemaining;
            }

            DateTime referralSignedDate = !hasEPC ? DateTime.MinValue : hc.DateReferralSigned.Date;
            DateTime hcExpiredDate      = !hasEPC ? DateTime.MinValue : referralSignedDate.AddYears(1);
            bool     isExpired          = !hasEPC ? true              : hcExpiredDate <= DateTime.Today;

            int nServicesLeft = 0;
            if (hc != null && DateTime.Today >= referralSignedDate.Date && DateTime.Today < hcExpiredDate.Date)
            {
                nServicesLeft = totalEpcsRemaining;
            }
            if (hc != null && totalServicesAllowedLeft < nServicesLeft)
            {
                nServicesLeft = totalServicesAllowedLeft;
            }

            bool has_valid_epc       = hasEPC && !isExpired && (hc.Organisation.OrganisationID == -2 || (hc.Organisation.OrganisationID == -1 && nServicesLeft > 0));
            int  epc_count_remaining = hasEPC && hc.Organisation.OrganisationID == -1 ? nServicesLeft : -1;

            dt.Rows[i]["has_valid_epc"]       = has_valid_epc;
            dt.Rows[i]["epc_expire_date"]     = hasEPC ? hcExpiredDate : (object)DBNull.Value;
            dt.Rows[i]["epc_count_remaining"] = epc_count_remaining != -1 ? epc_count_remaining : (object)DBNull.Value;

            dt.Rows[i]["most_recent_recall_sent"] = mostRecentRecallHashByPatientID[patientID] == null ? (object)DBNull.Value : ((LetterPrintHistory)mostRecentRecallHashByPatientID[patientID]).Date;
        }



        Session["registerpatienttoorg_data"] = dt;

        if (dt.Rows.Count > 0)
        {
            if (IsPostBack && Session["registerpatienttoorg_sortexpression"] != null && Session["registerpatienttoorg_sortexpression"].ToString().Length > 0)
            {
                DataView dataView = new DataView(dt);
                dataView.Sort = Session["registerpatienttoorg_sortexpression"].ToString();
                GrdRegistration.DataSource = dataView;
            }
            else
            {
                GrdRegistration.DataSource = dt;
            }


            try
            {
                GrdRegistration.DataBind();
                GrdRegistration.PagerSettings.FirstPageText = "1";
                GrdRegistration.PagerSettings.LastPageText  = GrdRegistration.PageCount.ToString();
                GrdRegistration.DataBind();
            }
            catch (Exception ex)
            {
                HideTableAndSetErrorMessage("", ex.ToString());
            }
        }
        else
        {
            dt.Rows.Add(dt.NewRow());
            GrdRegistration.DataSource = dt;
            GrdRegistration.DataBind();

            int TotalColumns = GrdRegistration.Rows[0].Cells.Count;
            GrdRegistration.Rows[0].Cells.Clear();
            GrdRegistration.Rows[0].Cells.Add(new TableCell());
            GrdRegistration.Rows[0].Cells[0].ColumnSpan = TotalColumns;
            GrdRegistration.Rows[0].Cells[0].Text       = "No Record Found";
        }

        if (hideFotter)
        {
            GrdRegistration.FooterRow.Visible = false;
        }
    }
Esempio n. 2
0
    public void CreateXML(Invoice[] invoices, bool validate = true)
    {
        if (validate)
        {
            Invoice[] tooOldList = GetInvoicesTooOldToClaim(invoices);
            if (tooOldList.Length > 0)
            {
                string invalids = string.Empty;
                foreach (Invoice i in tooOldList)
                {
                    invalids += (invalids.Length == 0 ? "" : ",") + i.InvoiceID.ToString();
                }
                throw new Exception("The following invoices are too old to claim: " + "<br />" + invalids);
            }
        }

        // get bulk invoice lines for less db calls in individual invoice create xml method  [invoiceID => list of invoicelines]
        Hashtable bulkInvoiceLineHash = InvoiceLineDB.GetBulkInvoiceLinesByInvoiceID(invoices);

        ArrayList allInvoiceLines = new ArrayList();

        foreach (DictionaryEntry pair in bulkInvoiceLineHash)
        {
            allInvoiceLines.AddRange((InvoiceLine[])pair.Value);
        }

        // get bluk health cards  [patientID=>healthcard]
        //
        // NB:
        // A DVA invoice can only use a DVA card
        // A Medicare invoice can only use a Medicare card
        // The system can only create a DVA invoice is if DVA is set as the active card (vice versa for Medicare)
        // So when a DVA invoice is created the DVA card was active, and then someone switches it to be the Medicare card thatis active.
        // So, it's correct to get only the DVA cards for DVA invoices (and Medicare cards for Medicare invoices), and also would be correct to ignore the active flag and just get the most recent.
        int[]     allPatientIDs      = GetAllPatientIDs((InvoiceLine[])allInvoiceLines.ToArray(typeof(InvoiceLine)));
        Hashtable bulkHealthCardHash = PatientsHealthCardsCacheDB.GetBullkMostRecent(allPatientIDs, claimType == ClaimType.Medicare ? -1 : -2);

        // get bluk staff provider numbers from registerstaff table
        int[]     allProviderStaffIDs   = GetAllProviderStaffIDs(invoices);
        Hashtable bulkRegisterStaffHash = RegisterStaffDB.Get2DHashByStaffIDOrgID(allProviderStaffIDs);
        Hashtable bulkStaffHash         = StaffDB.GetAllInHashtable(false, true, false, false);

        // get bluk healthcard actions to get EPC signed dates
        Hashtable bulkHealthCardActionsHash = HealthCardActionDB.GetReceivedActionsByPatientIDs(allPatientIDs);

        // get bluk epcreferrers
        Hashtable bulkEPCReferrersHash = PatientReferrerDB.GetEPCReferrersOf(allPatientIDs, false);

        // get all sites in one call
        Hashtable bulkSites = SiteDB.GetAllInHashtable();


        Hashtable claimNumberInvoiceGroups = new Hashtable();

        for (int i = 0; i < invoices.Length; i++)
        {
            if (claimNumberInvoiceGroups[(invoices[i]).HealthcareClaimNumber] == null)
            {
                claimNumberInvoiceGroups[(invoices[i]).HealthcareClaimNumber] = new ArrayList();
            }

            ((ArrayList)claimNumberInvoiceGroups[(invoices[i]).HealthcareClaimNumber]).Add(invoices[i]);
        }


        string noPatientFailures    = string.Empty;
        string noHealthcardFailures = string.Empty;

        foreach (string claimNbr in claimNumberInvoiceGroups.Keys)
        {
            Invoice[] invoiceList = (Invoice[])((ArrayList)claimNumberInvoiceGroups[claimNbr]).ToArray(typeof(Invoice));

            try
            {
                CreateXML(invoiceList, bulkInvoiceLineHash, bulkHealthCardHash, bulkRegisterStaffHash, bulkStaffHash, bulkSites, bulkHealthCardActionsHash, bulkEPCReferrersHash);
            }
            catch (HINXNoPatientOnInvoiceLineException ex)
            {
                noPatientFailures += (noPatientFailures.Length == 0 ? "" : "<br />") + ex.Message;
            }
            catch (HINXNoHealthcardException ex)
            {
                noHealthcardFailures += (noHealthcardFailures.Length == 0 ? "" : "<br />") + ex.Message;
            }
        }



        string errors = string.Empty;

        if (noPatientFailures.Length > 0)
        {
            errors += (errors.Length == 0 ? "" : "<br /><br />") + "The following invoices have invoices lines with no patient set (Fix this and re-generate): <br />" + noPatientFailures;
        }
        if (noHealthcardFailures.Length > 0)
        {
            errors += (errors.Length == 0 ? "" : "<br /><br />") + "The following invoices have patients with no " + (claimType == ClaimType.Medicare ? "Medicare" : "DVA") + " card set (Fix this and re-generate): <br />" + noHealthcardFailures;
        }
        if (errors.Length > 0)
        {
            throw new HINXUnsuccessfulItemsException(errors);
        }
    }
    protected void SetInvoiceInfo(Invoice invoice)
    {
        bool isDebug          = Request["debug"] != null && Request["debug"] == "1";
        bool useOnlyTestItems = false;

        SaveType saveType = Request.QueryString["reftag"] != null ? SaveType.Cancellation : SaveType.Claim;

        string receiptString = string.Empty;

        foreach (Receipt receipt in ReceiptDB.GetByInvoice(invoice.InvoiceID, false))
        {
            receiptString += (receiptString.Length == 0 ? "" : ", ") + "$" + receipt.Total.ToString();
        }

        string invoiceViewURL = "/Invoice_ViewV2.aspx?invoice_id=" + invoice.InvoiceID;

        lblInvoiceID.Text      = "<a href=\"" + invoiceViewURL + "\" onclick=\"open_new_tab('" + invoiceViewURL + "');return false;\">" + invoice.InvoiceID + "</a>";
        lblInvoiceTotal.Text   = "$" + invoice.Total.ToString();
        lblInvoiceOwing.Text   = "$" + invoice.TotalDue.ToString();
        lblReceiptedTotal.Text = "$" + invoice.ReceiptsTotal.ToString() + (invoice.CreditNotesTotal == 0 ? "" : " &nbsp;&nbsp;($" + invoice.CreditNotesTotal.ToString() + " Credit Noted)") + (invoice.RefundsTotal == 0 ? "" : " &nbsp;&nbsp;($" + invoice.RefundsTotal.ToString() + " Refunds)");
        lblDebtor.Text         = invoice.GetDebtor(true);
        lblBkDate.Text         = invoice.Booking.DateStart.ToString("d MMM, yyyy");
        lblBkOrgText.Text      = invoice.Booking.Organisation.IsAgedCare? "Facility" : "Clinic";
        lblBkOrg.Text          = invoice.Booking.Organisation.Name;

        System.Data.DataTable tbl = DBBase.GetGenericDataTable_WithWhereOrderClause(null, "Field", "field_id=" + invoice.Booking.Provider.Field.ID, "", "field_id", "descr");
        invoice.Booking.Provider.Field = IDandDescrDB.Load(tbl.Rows[0], "field_id", "descr");

        RegisterStaff regStaff = RegisterStaffDB.GetByStaffIDAndOrganisationID(invoice.Booking.Provider.StaffID, invoice.Booking.Organisation.OrganisationID);

        if (regStaff == null)
        {
            throw new CustomMessageException("Staff Member Not Set To This Clinic/Fac.");
        }

        InvoiceLine[] invLines = InvoiceLineDB.GetByInvoiceID(invoice.InvoiceID);
        Hashtable     patientHealthCardCache = PatientsHealthCardsCacheDB.GetBullkActive(invLines.Select(x => x.Patient.PatientID).ToArray());

        List <TyroHealthPointClaimIten> claimItems = new List <TyroHealthPointClaimIten>();

        for (int i = 0; i < invLines.Length; i++)
        {
            HealthCard hc = GetHealthCardFromCache(patientHealthCardCache, invLines[i].Patient.PatientID);

            string ptURL  = "PatientDetailV2.aspx?type=view&id=" + invLines[i].Patient.PatientID;
            string ptLink = "<a href=\"" + ptURL + "\" onclick=\"open_new_tab('" + ptURL + "');return false;\">" + invLines[i].Patient.Person.FullnameWithoutMiddlename + "</a>";

            if (hc == null)
            {
                throw new CustomMessageException("No healthcard found for " + ptLink + " (PT-ID:" + invLines[i].Patient.PatientID + ")");
            }
            if (hc.Organisation.OrganisationType.OrganisationTypeID != 150)
            {
                throw new CustomMessageException("Healthcard found for " + ptLink + " (PT-ID:" + invLines[i].Patient.PatientID + ") Is Not An Insurance Card");
            }

            /*
             * claim-amount:      claim amount in cents                    - max 10 digits
             * service-code:      item number service code                 - max 5  characters
             * description:       description of item to appear on receipt - max 32 characters
             * service-reference: body part or tooth number suffix         - max 3  characters
             * patient-id:        patient ID on card                       - exactly 2 digits
             * service-date:      claim date in YYYYMMDD format
             */

            isDebug = true;

            claimItems.Add(new TyroHealthPointClaimIten(
                               ((int)(invLines[i].Price * 100)).ToString(),
                               isDebug ? "F1234" : invLines[i].Offering.TacCompanyCode,
                               isDebug ? "Face"  : invLines[i].AreaTreated,
                               invLines[i].ServiceReference,
                               "",      // family number on card -- legally they have to enter it themselves
                               isDebug ? DateTime.Today.ToString("yyyyMMdd") : invoice.Booking.DateStart.ToString("yyyyMMdd")));
        }


        //useOnlyTestItems = true;

        // save variables & JSON array on the page accessable to JS to send to Tyro
        if (useOnlyTestItems)
        {
            claimItems = new List <TyroHealthPointClaimIten>();

            claimItems.Add(new TyroHealthPointClaimIten(
                               "10000",
                               "00001",
                               "SKULL XRAY",
                               "01",
                               "02",
                               DateTime.Today.ToString("yyyyMMdd")));

            claimItems.Add(new TyroHealthPointClaimIten(
                               "15000",
                               "00001",
                               "SKULL XRAY",
                               "01",
                               "02",
                               DateTime.Today.ToString("yyyyMMdd")));

            Page.ClientScript.RegisterStartupScript(this.GetType(), "invoice_items",
                                                    @"<script language=javascript>
                var _providerId       = '4237955J';
                var _serviceType      = 'D';
                var _claimItemsCount  = '2';
                var _totalClaimAmount = '25000';
                var _allClaimItems    = " + new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(claimItems) + @"; 
             </script>");
        }
        else
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "invoice_items",
                                                    @"<script language=javascript>
                    var _providerId       = '" + (isDebug ? "4237955J" : (regStaff.ProviderNumber.Length > 0 ? regStaff.ProviderNumber : invoice.Booking.Provider.ProviderNumber)) + @"';
                    var _serviceType      = '" + GetServiceTypeHashtable()[invoice.Booking.Provider.Field.Descr.ToLower()].ToString() + @"';
                    var _claimItemsCount  = '" + invLines.Length.ToString() + @"';
                    var _totalClaimAmount = '" + ((int)(invLines.Sum(item => item.Price) * 100)).ToString() + @"';
                    var _allClaimItems    = " + new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(claimItems) /* convert to JSON array */ + @"; 
                    " + (saveType == SaveType.Cancellation ? "var _refTag = " + Request.QueryString["reftag"] : string.Empty) + @"
                 </script>");
        }
    }
    protected void FillGrid()
    {
        DateTime fromDate = DateTime.MinValue; // IsValidDate(txtStartDate.Text) ? GetDate(txtStartDate.Text) : DateTime.MinValue;
        DateTime toDate   = IsValidDate(txtEndDate.Text)   ? GetDate(txtEndDate.Text)   : DateTime.MinValue;
        DateTime nNoRecallLettersAfterDate = IsValidDate(txtNoRecallLettersAfterDate.Text) ? GetDate(txtNoRecallLettersAfterDate.Text) : DateTime.MinValue;


        //DataTable dt = PatientDB.GetRecallPatients(fromDate, toDate, chkOnlyShowIfHasEPCs.Checked, Convert.ToInt32(ddlClinics.SelectedValue));
        DataTable dt = PatientDB.GetRecallPatients(fromDate, toDate, false, Convert.ToInt32(ddlClinics.SelectedValue));



        int[] patientIDs = new int[dt.Rows.Count];
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            patientIDs[i] = Convert.ToInt32(dt.Rows[i]["patient_patient_id"]);
        }


        Hashtable mostRecentRecallHashByPatientID = LetterPrintHistoryDB.GetMostRecentRecallHashByPatients(patientIDs);


        Hashtable patientHealthCardCache        = PatientsHealthCardsCacheDB.GetBullkActive(patientIDs);
        Hashtable epcRemainingCache             = GetEPCRemainingCache(patientHealthCardCache);
        Hashtable patientsMedicareCountCache    = PatientsMedicareCardCountThisYearCacheDB.GetBullk(patientIDs, DateTime.Today.Year);
        Hashtable patientsEPCRemainingCache     = PatientsEPCRemainingCacheDB.GetBullk(patientIDs, DateTime.Today.AddYears(-1));
        int       MedicareMaxNbrServicesPerYear = Convert.ToInt32(SystemVariableDB.GetByDescr("MedicareMaxNbrServicesPerYear").Value);


        ArrayList remainingPatientIDs = new ArrayList();

        dt.Columns.Add("epc_expire_date", typeof(DateTime));
        dt.Columns.Add("has_valid_epc", typeof(Boolean));
        dt.Columns.Add("epc_count_remaining", typeof(Int32));

        dt.Columns.Add("most_recent_recall_sent", typeof(DateTime));
        for (int i = dt.Rows.Count - 1; i >= 0; i--)
        {
            int patientID = Convert.ToInt32(dt.Rows[i]["patient_patient_id"]);

            HealthCard hc     = GetHealthCardFromCache(patientHealthCardCache, patientID);
            bool       hasEPC = hc != null && hc.DateReferralSigned != DateTime.MinValue;
            HealthCardEPCRemaining[] epcsRemaining = !hasEPC ? new HealthCardEPCRemaining[] { } : GetEPCRemainingFromCache(epcRemainingCache, hc);
            int totalServicesAllowedLeft           = !hasEPC ? 0 : (MedicareMaxNbrServicesPerYear - (int)patientsMedicareCountCache[patientID]);

            int totalEpcsRemaining = 0;
            for (int j = 0; j < epcsRemaining.Length; j++)
            {
                totalEpcsRemaining += epcsRemaining[j].NumServicesRemaining;
            }

            DateTime referralSignedDate = !hasEPC ? DateTime.MinValue : hc.DateReferralSigned.Date;
            DateTime hcExpiredDate      = !hasEPC ? DateTime.MinValue : referralSignedDate.AddYears(1);
            bool     isExpired          = !hasEPC ? true              : hcExpiredDate <= DateTime.Today;

            int nServicesLeft = 0;
            if (hc != null && DateTime.Today >= referralSignedDate.Date && DateTime.Today < hcExpiredDate.Date)
            {
                nServicesLeft = totalEpcsRemaining;
            }
            if (hc != null && totalServicesAllowedLeft < nServicesLeft)
            {
                nServicesLeft = totalServicesAllowedLeft;
            }

            bool has_valid_epc       = hasEPC && !isExpired && (hc.Organisation.OrganisationID == -2 || (hc.Organisation.OrganisationID == -1 && nServicesLeft > 0));
            int  epc_count_remaining = hasEPC && hc.Organisation.OrganisationID == -1 ? nServicesLeft : -1;

            dt.Rows[i]["has_valid_epc"]       = has_valid_epc;
            dt.Rows[i]["epc_expire_date"]     = hasEPC ? hcExpiredDate : (object)DBNull.Value;
            dt.Rows[i]["epc_count_remaining"] = epc_count_remaining != -1 ? epc_count_remaining : (object)DBNull.Value;

            dt.Rows[i]["most_recent_recall_sent"] = mostRecentRecallHashByPatientID[patientID] == null ? (object)DBNull.Value : ((LetterPrintHistory)mostRecentRecallHashByPatientID[patientID]).Date;

            // remove if no valid epc and set to show only those with a valid EPC
            if (!chkShowWithEPC.Checked && has_valid_epc)
            {
                dt.Rows.RemoveAt(i);
            }
            else if (!chkShowWithNoEPC.Checked && !has_valid_epc)
            {
                dt.Rows.RemoveAt(i);
            }
            else if (nNoRecallLettersAfterDate != DateTime.MinValue && mostRecentRecallHashByPatientID[patientID] != null && ((LetterPrintHistory)mostRecentRecallHashByPatientID[patientID]).Date.Date > nNoRecallLettersAfterDate)
            {
                dt.Rows.RemoveAt(i);
            }
            else
            {
                remainingPatientIDs.Add(patientID);
            }
        }

        hiddenPatientIDs.Value = string.Join(",", (int[])remainingPatientIDs.ToArray(typeof(int)));

        Session["recallpatientinfo_data"] = dt;


        if (dt.Rows.Count > 0)
        {
            if (IsPostBack && Session["recallpatientinfo_sortexpression"] != null && Session["recallpatientinfo_sortexpression"].ToString().Length > 0)
            {
                DataView dataView = new DataView(dt);
                dataView.Sort         = Session["recallpatientinfo_sortexpression"].ToString();
                GrdPatient.DataSource = dataView;
            }
            else
            {
                GrdPatient.DataSource = dt;
            }


            try
            {
                GrdPatient.DataBind();
                GrdPatient.PagerSettings.FirstPageText = "1";
                GrdPatient.PagerSettings.LastPageText  = GrdPatient.PageCount.ToString();
                GrdPatient.DataBind();
            }
            catch (Exception ex)
            {
                SetErrorMessage("", ex.ToString());
            }
        }
        else
        {
            dt.Rows.Add(dt.NewRow());
            GrdPatient.DataSource = dt;
            GrdPatient.DataBind();

            int TotalColumns = GrdPatient.Rows[0].Cells.Count;
            GrdPatient.Rows[0].Cells.Clear();
            GrdPatient.Rows[0].Cells.Add(new TableCell());
            GrdPatient.Rows[0].Cells[0].ColumnSpan = TotalColumns;
            GrdPatient.Rows[0].Cells[0].Text       = "No Record Found";
        }
    }