//using NPOI.HSSF.UserModel;
//using NPOI.HSSF.Util;
//using NPOI.SS.UserModel;
//using NPOI.SS.Util;
using DevExpress.Web;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using System;
using System.Collections;
using System.Data;
using System.Globalization;
using System.IO;
using System.Resources;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Reports_TA_UI_Report_PayrollGridReport : Base.BasePage
{
    #region Variable Declaration
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    DataSet ds_Checkuser = new DataSet();
    GetReports rptEmp = new GetReports();
    Rpt_Common rptcommon = new Rpt_Common();
    ResourceManager rm;
    CultureInfo ci;
    cls_Common objCommon = new cls_Common();
    EmployeeEventData objEmployee = new EmployeeEventData();
    PayrollConfigurationEventData objPayrollData = new PayrollConfigurationEventData();

    string strFromdate, gstrDateFormat, strTodate;
    int intIndividualUser = 0;
    DateTime dtFromDate1, dtToDate1;
    DataSet dsEmp = new DataSet();
    int rowIndex1 = 0, day = 0;
    TimeSpan diff;
    int employeeCategory = 0, employeeType = 0;
    string empName = "", empId = "", Level = "", strScript = "", strReportType = string.Empty, ParenetLevelid = string.Empty;
    string strSwipeCard = "", strdtFromDate, strdtToDate, SelectedMonth = "", SelectedYear = "";
    #endregion
    #region Page Load event
    /// <summary>
    /// On page loading
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    /// 

    //protected void page_Init (object sender,EventArgs e)
    //{
    //    if (ViewState["gridData"] != null)
    //    {
    //        txtOtherAllowance_TextChanged(sender,e);
    //    }

    //}

    protected override void Page_Load(object sender, EventArgs e)
    { // session checking
        base.Page_Load(sender, e);
        //get the culture info to set the language        
        if (!Page.IsPostBack)
        {
            base.CheckPages(0);
            objCommon.menu("Payroll Report", "320");
        }

        DataSet dsDataGrid = new DataSet();
        dsDataGrid = (DataSet)ViewState["gridData"];


        //if(dsDataGrid!=null)
        //{
        //    gvData.DataSource = (DataSet)ViewState["gridData"];
        //    gvData.DataBind();
        //}
        //else
        //{
        //    gvData.DataSource = null;
        //    gvData.DataBind();
        //}

        string source_Language;
        source_Language = Convert.ToString(Session["Session_ActiveLanguage"]);
        rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
        ci = Thread.CurrentThread.CurrentCulture;
        site.SiteMapProvider = Convert.ToString(Session["SiteMapProvider"]);
        LoadStrings(ci);
        //gvData.Styles.CssFilePath = Convert.ToString(Session["GridCSS"]);
        //gvData.DataSource = null;
        //gvData.DataBind();
        //gvDataDetailed.Styles.CssFilePath = Convert.ToString(Session["GridCSS"]);
        string strSetAlert = "";
        strSetAlert = strSetAlert + "<script language='javascript'>";
        strSetAlert = strSetAlert + "SetAlertMessages('" + rm.GetString("Alert_EnterDate", ci) + "','" + rm.GetString("Alert_EnterToDate", ci) + "');";
        strSetAlert = strSetAlert + "MaxLengthh('" + rm.GetString("Alert_MaximumLengthis", ci) + "');";
        strSetAlert = strSetAlert + "SetAlertCheckDate('" + rm.GetString("Alert_Validmonthdatefourdigit", ci) + "','" + rm.GetString("Alert_Validdatemonthfourdigit", ci) + "','" + rm.GetString("Alert_Invalidyearentry", ci) + "','" + rm.GetString("Alert_Invalidmonthentry", ci) + "','" + rm.GetString("Alert_Invaliddateentry", ci) + "','" + rm.GetString("Alert_IncorrectdateformatDDMONYYYY", ci) + "','" + rm.GetString("Alert_Entertime", ci) + "','" + rm.GetString("Alert_Invalidvalueforhours", ci) + "','" + rm.GetString("Alert_Invalidvalueforminites", ci) + "','" + rm.GetString("Alert_Invalidtimeformat1", ci) + "','" + rm.GetString("Alert_PleaseentervalidDateandTime", ci) + "','" + rm.GetString("Alert_ValiddatemonthMMDDYYHHMM", ci) + "','" + rm.GetString("Alert_ValiddatemonthMMDDYYHHMMTT", ci) + "','" + rm.GetString("Alert_PleaseentervalidDateandTime", ci) + "','" + rm.GetString("Alert_Invalidvalueforhours", ci) + "','" + rm.GetString("Alert_Invalidvalueforminites", ci) + "');";
        strSetAlert = strSetAlert + "</script>";
        Page.RegisterStartupScript("SetAlertMessages", strSetAlert);
        //Set UserRights
        UserRights();
        if (!IsPostBack)
        {
            Hidden1.Value = Session["IDateFormat"].ToString();
            // Bindings the employee category and type.
            BindingEmployeeCategoryandType();
            FillDesignation();
            // fillShift();
            if (Request.QueryString["Source"] != null)
            {
                if (Request.QueryString["Source"].ToString() == "Email")
                {
                    divdateTime.Visible = false;
                    trView.Visible = false;
                    trSave.Visible = true;
                    if (Request.QueryString["ScheduleId"] != null)
                    {
                        DataSet ds = new DataSet();
                        ds = rptEmp.GetEmailSchedulerFilterDetails(Convert.ToInt32(Request.QueryString["ScheduleId"]));
                        if (ds.Tables.Count > 0)
                        {
                            if (ds.Tables[0].Rows.Count > 0)
                            {
                                txtEmployeeName.Text = Convert.ToString(ds.Tables[0].Rows[0]["EmployeeName"]);
                                ddlEmpCatagory.SelectedValue = Convert.ToString(ds.Tables[0].Rows[0]["EmployeeCategory"]);
                                ddlDesignation.SelectedValue = Convert.ToString(ds.Tables[0].Rows[0]["DesignationID"]);
                                txtEmployeeId.Text = Convert.ToString(ds.Tables[0].Rows[0]["EmployeeID"]);
                                ddlGender.SelectedValue = Convert.ToString(ds.Tables[0].Rows[0]["Gender"]);
                                ddlEmpType.SelectedValue = Convert.ToString(ds.Tables[0].Rows[0]["EmployeeType"]);
                                Session["EMailParentId"] = Convert.ToString(ds.Tables[0].Rows[0]["ParentID"]);
                            }
                        }
                    }
                    else
                    {
                        if (Convert.ToString(Session["hdnReportFilters"]) != string.Empty)
                        {
                            string strhdnParameters = Convert.ToString(Session["hdnReportFilters"]);
                            string[] strArray = new string[50];
                            string[] strArray1 = new string[50];
                            strArray = strhdnParameters.Split(',');
                            for (int i = 0; i < strArray.Length; i++)
                            {
                                string[] strTemp = new string[5];
                                strTemp = strArray[i].Split('=');
                                strArray1[i] = strTemp[1];
                            }
                            txtEmployeeId.Text = strArray1[2].ToString().Replace("~", ",");

                            txtEmployeeName.Text = strArray1[4].ToString().Replace("~", ",");
                            ddlEmpCatagory.SelectedValue = strArray1[6].ToString();
                            ddlEmpType.SelectedValue = strArray1[7].ToString();
                            ddlDesignation.SelectedValue = Convert.ToString(strArray1[11]);
                            ddlGender.SelectedValue = Convert.ToString(strArray1[12]);
                            Session["EMailParentId"] = Convert.ToString(strArray1[10]);
                        }
                    }
                }
            }
            else
            {
                divdateTime.Visible = true;
                trView.Visible = true;
                trSave.Visible = false;
            }
            if (Request.QueryString["ScheduleId"] != null)
            {
                string strGet = hdnReportFilters.Value;
                string strScript = "<script language='javascript' type='text/javascript'>";
                strScript += "GethiddenValue();";
                strScript += " </script>";
                this.RegisterStartupScript("setScript", strScript);
            }
            ddlDesignation.PreRender += LB_PreRender;
            txtFromDate.Text = (Convert.ToDateTime(objCommon.CurrentMonthStartDate())).ToString(Session["MDateFormat"].ToString());
            txtToDate.Text = (Convert.ToDateTime(System.DateTime.Now.ToShortDateString())).ToString(Session["MDateFormat"].ToString());
        }
        //Check whether the employee is Individual User
        intIndividualUser = objCheckUser.CheckIndividualUser(Convert.ToString(Session["UserGroupName"]));
        if (intIndividualUser >= 1)
        {
            PlaceHolderMonthlyAttendance.Controls.Clear();
            divEmployeeDetails.Visible = false;
        }
        //Convert date time to MM/dd/YYYY format
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        strFromdate = txtFromDate.Text;
        strFromdate = objCommon.DateConvertion(gstrDateFormat, strFromdate);
        strTodate = txtToDate.Text;
        strTodate = objCommon.DateConvertion(gstrDateFormat, strTodate);
        if (Page.MasterPageFile.ToString() == "TA_Popup_Report_MasterPage.master")
        {
            conHeader.Visible = false;
        }

    }
    protected void Page_PreInit(object sender, EventArgs e)
    {
        if (Request.QueryString["Source"] != null)
            this.Page.MasterPageFile = "TA_Popup_Report_MasterPage.master";
    }
   
    private void FillDesignation()
    {
        DataSet ds_designation = new DataSet();
        ds_designation = objEmployee.select_CommonDesignation();
        if (ds_designation != null)
        {
            if (ds_designation.Tables[0].Rows.Count > 0)
            {
                ddlDesignation.DataSource = ds_designation;
                ddlDesignation.DataTextField = "TitleName";
                ddlDesignation.DataValueField = "TitleId";
                ddlDesignation.DataBind();
            }
            ds_designation.Dispose();
            foreach (ListItem item in ddlDesignation.Items)
            {
                item.Attributes.Add("title", item.Text);
            }
        }
    }
    /// <summary>
    /// Bindings the employee category and type.
    /// </summary>
    private void BindingEmployeeCategoryandType()
    {
        // employee category binding
        DataSet dsCategory = new DataSet();
        dsCategory = objEmployee.SelectCategoryDetailsEmployee("");
        if (dsCategory != null)
        {
            if (dsCategory.Tables[0].Rows.Count > 0)
            {
                ddlEmpCatagory.DataSource = dsCategory;
                ddlEmpCatagory.DataTextField = "CategoryName";
                ddlEmpCatagory.DataValueField = "CategoryId";
                ddlEmpCatagory.DataBind();
            }
            dsCategory.Dispose();
            foreach (ListItem item in ddlEmpCatagory.Items)
            {
                item.Attributes.Add("title", item.Text);
            }
        }
        // employee type binding
        DataSet dsType = new DataSet();
        dsType = objEmployee.SelectTypeDetailsEmployee("");
        if (dsType != null)
        {
            if (dsType.Tables[0].Rows.Count > 0)
            {
                ddlEmpType.DataSource = dsType;
                ddlEmpType.DataTextField = "TypeName";
                ddlEmpType.DataValueField = "TypeId";
                ddlEmpType.DataBind();
            }
            dsType.Dispose();
            foreach (ListItem item in ddlEmpType.Items)
            {
                item.Attributes.Add("title", item.Text);
            }
        }
    }
    /// <summary>
    /// Validate the FromDate
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>
    public void ValidateFromDate(object s, ServerValidateEventArgs e)
    {
        try
        {
            strFromdate = txtFromDate.Text;
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            strFromdate = objCommon.DateConvertion(gstrDateFormat, strFromdate);
            DateTime dtCurrentDate = Convert.ToDateTime(DateTime.Today.Date);
            DateTime dtFromDate = DateTime.Parse(strFromdate);
            TimeSpan diff = dtFromDate.Subtract(dtCurrentDate);
            int day = diff.Days;
            if (day <= 0)
                e.IsValid = true;
            else
            {
                base.Message(rm.GetString("Alert_EnterValidFromDate", ci));
                e.IsValid = false;
            }
        }
        catch
        {
            //
        }
    }
    /// <summary>
    /// Validate the ToDate
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>
    public void ValidateToDate(object s, ServerValidateEventArgs e)
    {
        try
        {
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            strTodate = txtToDate.Text;
            strTodate = objCommon.DateConvertion(gstrDateFormat, strTodate);
            DateTime dtCurrentDate = Convert.ToDateTime(DateTime.Today.Date);
            DateTime dtFromDate = DateTime.Parse(strTodate);
            TimeSpan diff = dtFromDate.Subtract(dtCurrentDate);
            int day = diff.Days;
            if (day <= 0)
                e.IsValid = true;
            else
            {
                base.Message(rm.GetString("Alert_EnterValidToDate", ci));
                e.IsValid = false;
            }
        }
        catch
        {
        }
    }
    /// <summary>
    /// Compare ToDate with FromDate
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>
    public void CompareDate(object s, ServerValidateEventArgs e)
    {
        try
        {
            strFromdate = txtFromDate.Text;
            strTodate = txtToDate.Text;
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            strTodate = objCommon.DateConvertion(gstrDateFormat, strTodate);
            strFromdate = objCommon.DateConvertion(gstrDateFormat, strFromdate);
            DateTime dtToDate = DateTime.Parse(strTodate);
            DateTime dtFromDate = DateTime.Parse(strFromdate);
            TimeSpan diff = dtToDate.Subtract(dtFromDate);
            int day = diff.Days;
            if (day >= 0)
                e.IsValid = true;
            else
            {
                base.Message(rm.GetString("Msg_SelectvaliddatecomparewithFromdate", ci));
                e.IsValid = false;
            }
        }
        catch
        {
        }
    }
    /// <summary>
    /// Load Shift DropDown
    /// </summary>
    /// <summary>
    /// Getting Information from resource file and display it in label
    /// </summary>
    /// <param name="ci"></param>
    private void LoadStrings(CultureInfo ci)
    {
        lblFilter.Text = rm.GetString("lblFilter", ci);
        btn_View.Text = "&nbsp;&nbsp;" + rm.GetString("btn_View", ci);
        lblPayrollGridReport.Text = rm.GetString("Report_GeneratePayrollAttendanceHeader", ci);
        lblEmployeeName.Text = rm.GetString("email_EmployeeName", ci);
        lblEmployeeId.Text = rm.GetString("email_EmployeeId", ci);
        lblEmpCategory.Text = rm.GetString("Master_Category", ci);
        lblEmpType.Text = rm.GetString("Master_Type", ci);
        lblTimePeriod.Text = rm.GetString("Reports_TimePeriod", ci);
        lblFrom.Text = rm.GetString("email_FromDate", ci);
        lblTo.Text = rm.GetString("email_ToDate", ci);
        reqFromDate.ErrorMessage = rm.GetString("Alert_PleaseselectFromDate", ci);
        reqToDate.ErrorMessage = rm.GetString("Alert_PleaseselectToDate", ci);
        ddlEmpCatagory.Items[0].Text = rm.GetString("Select", ci);
        ddlEmpType.Items[0].Text = rm.GetString("Select", ci);
        lblDesignation.Text = rm.GetString("EmployeeMaster_Designation", ci);
        lblGender.Text = rm.GetString("EmployeeMaster_Gender", ci);
        ddlGender.Items[0].Text = rm.GetString("Caption_Both", ci);
        ddlGender.Items[1].Text = rm.GetString("rbtn_EmployeeMaster_Male", ci);
        ddlGender.Items[2].Text = rm.GetString("rbtn_EmployeeMaster_Female", ci);
        ddlDesignation.Items[0].Text = rm.GetString("ExportData_All", ci);
        btnSave.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Save", ci);
        btnBack.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Cancel", ci);
        //btn_Export.Text = "&nbsp;&nbsp;" + rm.GetString("btn_ExporttoExcel", ci);
        lblDateFilter.Text = rm.GetString("lbl_DateFilter", ci);
        rbCustom.Text = rm.GetString("rb_Custom", ci);
        rbpreviousMonth.Text = rm.GetString("rb_PreviousMonth", ci);

        rbThisMonth.Text = rm.GetString("rb_ThisMonth", ci);

    }
    /// <summary>
    /// To check rights for the logged in user
    /// </summary>
    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(322, Convert.ToInt32(Session["userGroup_Id"]), "viewPrv");
        if (ds_Checkuser.Tables[0].Rows.Count > 0)
        {
            if (ds_Checkuser.Tables[0].Rows[0]["viewPrv"] == DBNull.Value || Convert.ToInt32(ds_Checkuser.Tables[0].Rows[0]["viewPrv"]) == 1)
            {
                btn_View.Visible = true;
            }
            else
            {
                btn_View.Visible = false;
            }
        }
        else
        {
            Response.Redirect("ReportsLandingPage.aspx");
        }
    }
    /// <summary>
    /// To apply tooltip for the designation in the drop down
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void LB_PreRender(object sender, System.EventArgs e)
    {
        foreach (ListItem item in ddlDesignation.Items)
        {
            item.Attributes.Add("title", item.Text);
        }
    }
    /// <summary>
    /// Export to excel Functionality operation
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ExportExcel(DataSet dsEmp, DataTable dtLevelName)
    {
        HSSFWorkbook workbook = new HSSFWorkbook();
        ISheet sheet = workbook.CreateSheet("Payslip Report");
        int rowIndex = 0;

        NPOI.SS.UserModel.IRow row = sheet.CreateRow(rowIndex);
        HSSFFont hFont = (HSSFFont)workbook.CreateFont();
        hFont.Boldweight = (short)FontBoldWeight.Bold;
        hFont.Color = HSSFColor.Maroon.Index;
        hFont.FontHeightInPoints = 10;
        HSSFCellStyle hStyle = (HSSFCellStyle)workbook.CreateCellStyle();
        hStyle.SetFont(hFont);
        hStyle.FillForegroundColor = IndexedColors.White.Index;
        hStyle.FillPattern = FillPattern.SolidForeground;
        hStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
        hStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
        hStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
        hStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
        HSSFCellStyle MainStyle = (HSSFCellStyle)workbook.CreateCellStyle();
        MainStyle.SetFont(hFont);
        MainStyle.Alignment = HorizontalAlignment.Center;
        HSSFCellStyle hStyle2 = (HSSFCellStyle)workbook.CreateCellStyle();
        hStyle2.SetFont(hFont);
        HSSFCellStyle IStyle = (HSSFCellStyle)workbook.CreateCellStyle();
        IStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
        IStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
        IStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
        IStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
        string NewTimeFormat = string.Empty;
        string TimeFormat = Convert.ToString(Session["ITimeFormat"]);
        if (TimeFormat == "HH:mm")
        {
            NewTimeFormat = "HH:mm";
        }
        else
        {
            NewTimeFormat = "hh:mm tt";
        }
        if (dtLevelName.Rows.Count > 0)
        {
            row.CreateCell(0).SetCellValue(Convert.ToString(dtLevelName.Rows[0][0]));
            sheet.AddMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 0, 13));
            row.GetCell(0).CellStyle = MainStyle;
            rowIndex++;
            row = sheet.CreateRow(rowIndex);
        }

        row.CreateCell(0).SetCellValue("PaySlip Report From - " + Convert.ToString(txtFromDate.Text) + " To - " + Convert.ToString(txtToDate.Text));
        row.GetCell(0).CellStyle = MainStyle;
        sheet.AddMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 0, 13));
        rowIndex++;
        row = sheet.CreateRow(rowIndex);
        rowIndex++;
        row = sheet.CreateRow(rowIndex);
        double Valworkhrs = 0.0, ValExcesshrs = 0.0;
        row.CreateCell(0).SetCellValue("Sl.No");
        row.CreateCell(1).SetCellValue("Employee Id");
        row.CreateCell(2).SetCellValue("Employee Name");
        row.CreateCell(3).SetCellValue("Designation");
        row.CreateCell(4).SetCellValue("Date");
        row.CreateCell(5).SetCellValue("Punch Type");
        row.CreateCell(6).SetCellValue("In Date");
        row.CreateCell(7).SetCellValue("In Time");
        row.CreateCell(8).SetCellValue("Punch Type");
        row.CreateCell(9).SetCellValue("Out Date");
        row.CreateCell(10).SetCellValue("Out Time");
        row.CreateCell(11).SetCellValue("Total # of hours Worked(hh:mm)");
        row.CreateCell(12).SetCellValue("Excess / Discrepancy hours(hh:mm)");
        row.CreateCell(13).SetCellValue("Remarks");

        //row.RowStyle = hStyle;
        for (int i = 0; i <= 13; i++)
        {
            row.GetCell(i).CellStyle = hStyle;
        }
        rowIndex++;
        string strPre = string.Empty; int EmployeeDatacount = 1;

        Int64 TotalMinsWorked = 0;
        string TotalMinsWorkedString;
        TimeSpan TS_TotalMinsWorked;
        double VC_TotalHrsWorked = 00.00;

        foreach (DataRow DR in dsEmp.Tables[0].Rows)
        {
            row = sheet.CreateRow(rowIndex);

            if (strPre == string.Empty || strPre != Convert.ToString(DR["Employee_Id"]))
            {
                if (EmployeeDatacount > 1)
                {
                    row = sheet.CreateRow(rowIndex);
                    row.CreateCell(10).SetCellValue("Sub-Total:");
                    row.GetCell(10).CellStyle = hStyle;

                    TS_TotalMinsWorked = TimeSpan.FromMinutes(Valworkhrs);
                    //       TS_TotalMinsWorked = (1 == Convert.ToString(Valworkhrs / 60).Length ? "0" + Convert.ToString(Valworkhrs / 60) : Convert.ToString(Valworkhrs / 60)) + ":" + (1 == Convert.ToString(Valworkhrs % 60).Length ? "0" +
                    //Convert.ToString(Valworkhrs % 60) : Convert.ToString(Valworkhrs % 60));
                    row.CreateCell(11).SetCellValue(string.Format("{0:00}:{1:00}", (int)TS_TotalMinsWorked.TotalHours, TS_TotalMinsWorked.Minutes));

                    // row.CreateCell(11).SetCellValue(Convert.ToString(TS_TotalMinsWorked));
                    row.GetCell(11).CellStyle = hStyle;
                    Valworkhrs = 0.0;

                    //row.CreateCell(12).SetCellValue(Convert.ToString(ValExcesshrs));
                    //row.GetCell(12).CellStyle = hStyle;
                    //ValExcesshrs = 0.0;

                    rowIndex++;
                }
                row = sheet.CreateRow(rowIndex);
                row.CreateCell(0).SetCellValue(Convert.ToString(EmployeeDatacount));
                EmployeeDatacount++;
            }
            else
            {
                row.CreateCell(0).SetCellValue(string.Empty);
            }
            row.CreateCell(1).SetCellValue(Convert.ToString(DR["Employee_Id"]));
            row.CreateCell(2).SetCellValue(Convert.ToString(DR["empName"]));
            row.CreateCell(3).SetCellValue(Convert.ToString(DR["Designation"]));
            row.CreateCell(4).SetCellValue(Convert.ToString(DR["Date"]));
            row.CreateCell(5).SetCellValue(Convert.ToString(DR["Inpunch"]));
            row.CreateCell(6).SetCellValue(Convert.ToString(DR["Indate"]));
            if (Convert.ToString(DR["Intime"]) == String.Empty)
                row.CreateCell(7).SetCellValue(Convert.ToString(DR["Intime"]));
            else
            {
                row.CreateCell(7).SetCellValue((Convert.ToDateTime(Convert.ToString(DR["Intime"]))).ToString(NewTimeFormat));
            }
            //  row.CreateCell(7).SetCellValue(Convert.ToString(DR[""]));
            row.CreateCell(8).SetCellValue(Convert.ToString(DR["Outpunch"]));
            row.CreateCell(9).SetCellValue(Convert.ToString(DR["Outdate"]));
            if (Convert.ToString(DR["Outtime"]) == String.Empty)
                row.CreateCell(10).SetCellValue(Convert.ToString(DR["Outtime"]));
            else
            {
                row.CreateCell(10).SetCellValue((Convert.ToDateTime(Convert.ToString(DR["Outtime"]))).ToString(NewTimeFormat));
            }
            //  row.CreateCell(10).SetCellValue(Convert.ToString(DR[""]));

            TotalMinsWorked = Convert.ToInt64(DR["TotalMinsWorked"]);
            VC_TotalHrsWorked = VC_TotalHrsWorked + Convert.ToDouble(DR["TotalMinsWorked"]);
            TotalMinsWorkedString = (1 == Convert.ToString(TotalMinsWorked / 60).Length ? "0" + Convert.ToString(TotalMinsWorked / 60) :
               Convert.ToString(TotalMinsWorked / 60)) + ":" + (1 == Convert.ToString(TotalMinsWorked % 60).Length ? "0" +
               Convert.ToString(TotalMinsWorked % 60) : Convert.ToString(TotalMinsWorked % 60));

            TotalMinsWorked = 0;
            //  row.CreateCell(14).SetCellValue(Convert.ToString(EarlyexitString));

            row.CreateCell(11).SetCellValue(Convert.ToString(TotalMinsWorkedString));
            if (Convert.ToString(DR["Excess"]) == "-")
            { row.CreateCell(12).SetCellValue(Convert.ToString("00:00")); }
            else
            { row.CreateCell(12).SetCellValue(Convert.ToString(DR["Excess"])); }
            row.CreateCell(13).SetCellValue(Convert.ToString(DR["Remarks"]));
            //sheet.AddMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 13, 20));
            Valworkhrs = Valworkhrs + Convert.ToDouble(VC_TotalHrsWorked);
            VC_TotalHrsWorked = 0.0;
            //   ValExcesshrs = ValExcesshrs + Convert.ToDouble(DR["Excess"]);
            strPre = Convert.ToString(DR["Employee_Id"]);
            for (int i = 0; i <= 13; i++)
            {
                row.GetCell(i).CellStyle = IStyle;
                sheet.AutoSizeColumn(i);
            }
            rowIndex++;

        }
        row = sheet.CreateRow(rowIndex);
        row.CreateCell(10).SetCellValue("Sub-Total:");
        row.GetCell(10).CellStyle = hStyle;

        TS_TotalMinsWorked = TimeSpan.FromMinutes(Valworkhrs);
        //       TS_TotalMinsWorked = (1 == Convert.ToString(Valworkhrs / 60).Length ? "0" + Convert.ToString(Valworkhrs / 60) : Convert.ToString(Valworkhrs / 60)) + ":" + (1 == Convert.ToString(Valworkhrs % 60).Length ? "0" +
        //Convert.ToString(Valworkhrs % 60) : Convert.ToString(Valworkhrs % 60));
        row.CreateCell(11).SetCellValue(string.Format("{0:00}:{1:00}", (int)TS_TotalMinsWorked.TotalHours, TS_TotalMinsWorked.Minutes));

        // row.CreateCell(11).SetCellValue(Convert.ToString(TS_TotalMinsWorked));
        row.GetCell(11).CellStyle = hStyle;
        Valworkhrs = 0.0;
        rowIndex++;

        using (MemoryStream exportData = new MemoryStream())
        {
            workbook.Write(exportData);
            string saveAsFileName;
            saveAsFileName = string.Format("GeneralMonthlyAttendanceReport-{0:d}.xls", DateTime.Now).Replace("/", "-");
            Response.ContentType = "application/vnd.ms-excel";
            Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", saveAsFileName));
            Response.Clear();
            Response.BinaryWrite(exportData.GetBuffer());
            //Response.End();
            HttpContext.Current.ApplicationInstance.CompleteRequest();
        }
    }
    #endregion
    #region Button Events
    protected void btn_View_Click(object sender, EventArgs e)
    {
        string strSwipeCard = "";
        string Level = string.Empty;
        string employeeName = string.Empty;
        string empName = string.Empty;
        string empId = string.Empty;
        int shift;
        if (Page.IsValid == true)
        {
            string dtFrom = "", dtTo = "";
            if (txtFromDate.Text != "")
                dtFrom = strFromdate;
            if (txtToDate.Text != "")
                dtTo = strTodate;

            if (intIndividualUser >= 1)
            {
                empName = string.Empty;
                Level = string.Empty;
                empId = Convert.ToString(Session["EmployeeCodeId"]);
            }
            else
            {
                empName = Convert.ToString(txtEmployeeName.Text);
                empId = Convert.ToString(txtEmployeeId.Text.Trim());
                employeeName = this.txtEmployeeName.Text.Replace("'", "''");
                Level = rptcommon.getNodes(Convert.ToInt16(Session["parentLevelId"]), Convert.ToString(Session["LevelRights"]));
            }
            string strScript = "";
            strScript = strScript + "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>";
            strScript = strScript + "<meta http-equiv='X-UA-Compatible' content='IE=edge' />";
            strScript = strScript + "<script language='javascript'>";
            strScript = strScript + "window.open('TA_UI_Report_ReportViewer.aspx?ReportName=Payslip&dtFrom=" + dtFrom
                + "&dtTo=" + dtTo + "&empid=" + empId + "&EmpName=" + employeeName + "&Level=" + Level
                + "&EmpCategory=" + Convert.ToInt32(ddlEmpCatagory.SelectedValue) + "&EmpType=" + Convert.ToInt32(ddlEmpType.SelectedValue)
                + "&ParentLevelId=" + Convert.ToInt16(Session["parentLevelId"])
                + "&UserGroupName=" + Session["UserGroupName"].ToString() + "&GradeLevel=" + Convert.ToString(Session["GradeLevel"])
                + "&SwipeCard=" + empId + "&Designation=" + Convert.ToInt32(ddlDesignation.SelectedValue)
                + "&Gender=" + ddlGender.SelectedValue + "','','left=140px, top=60px, width=1000px, height=600px, scrollbars=yes, status=no, resizable=yes');";
            strScript = strScript + "</script>";
            Response.Write(strScript);
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            if(ViewState["gridData"]!=null)
            {
                DataSet dsInsertTbl = (DataSet)ViewState["gridData"];

                DateTime dt = DateTime.Parse(txtFromDate.Text);
                Hashtable htable = new Hashtable();

                DataSet ds = new DataSet();
                
                if (dsInsertTbl.Tables[0].Rows.Count>0)
                {
                    String count = string.Empty;

                    foreach (DataRow row in dsInsertTbl.Tables[0].Rows)
                    {
                        htable.Add("@tag", "S");
                        htable.Add("@EmployeeCodeID", Convert.ToString(row["Employee_Code_Id"]));
                        htable.Add("@PayslipMonth", Convert.ToString(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(dt.Month)));
                        htable.Add("@year", Convert.ToString(dt.Year));

                        ds = objPayrollData.InsertPayslipReportData(htable);

                        if(ds.Tables[0].Rows.Count>0)
                        {
                            ds.Clear();
                            htable.Clear();

                            htable.Add("@tag", 'U');
                            htable.Add("@EmployeeName", Convert.ToString(row["EmployeeName"]));
                            htable.Add("@EmployeeCodeID", Convert.ToString(row["Employee_Code_Id"]));
                            htable.Add("@Designation", Convert.ToString(row["Designation"]));
                            htable.Add("@Gender", Convert.ToString(row["Gender"]));
                            htable.Add("@PayslipMonth", Convert.ToString(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(dt.Month)));
                            htable.Add("@year", Convert.ToString(dt.Year));
                            htable.Add("@Calender_Days", Convert.ToInt32(row["Calender_Days"]));
                            htable.Add("@PD", Convert.ToInt32(row["Present_Days"]));
                            htable.Add("@AD", Convert.ToInt32(row["Absent_Days"]));
                            htable.Add("@LD", Convert.ToInt32(row["Leave_Days"]));
                            htable.Add("@WOD", Convert.ToInt32(row["Weekly_OFF_Days"]));
                            htable.Add("@HD", Convert.ToInt32(row["Holiday_Days"]));
                            htable.Add("@LOPD", Convert.ToInt32(row["LossofPay_Days"]));
                            htable.Add("@TotalOT", Convert.ToString(row["TotalOTHrs"]));
                            htable.Add("@CTC", Convert.ToInt64((row["CostToCompany"])));
                            htable.Add("@BasicSalary", Convert.ToInt64(row["BasicSalary"]));
                            htable.Add("@DA", Convert.ToInt64(row["Dearness_Allowance"]));
                            htable.Add("@HRA", Convert.ToInt64(row["HouseRent_Allowance"]));
                            htable.Add("@EarnedAmount", Convert.ToInt64(row["EarnedAmount"]));
                            htable.Add("@CA", Convert.ToInt64(Convert.ToString(row["Conveyance_Allowance"]) == String.Empty ? "0" : Convert.ToString(row["Conveyance_Allowance"])));
                            htable.Add("@MA", Convert.ToInt64(row["Medical_Allowance"]));
                            htable.Add("@CEA", Convert.ToInt64(row["Children_Education_Allowance"]));
                            htable.Add("@OA", Convert.ToInt64(row["OA"]));
                            htable.Add("@Tds_PolicyId", Convert.ToInt32(row["Tds_PolicyId"]));
                            htable.Add("@PF", Convert.ToInt64(Convert.ToString(row["ProvidentFund"]) == String.Empty ? "0" : Convert.ToString(row["ProvidentFund"])));
                            htable.Add("@ESI", Convert.ToInt64(Convert.ToString(row["ESI"]) == String.Empty ? "0" : Convert.ToString(row["ESI"])));
                            if (Convert.ToString(row["LoanCount"]) == "")
                            {
                                htable.Add("@LoanCount", Convert.ToInt64(0));
                                htable.Add("@LoanDueAmount", Convert.ToInt64(0));
                            }
                            else
                            {
                                htable.Add("@LoanCount", Convert.ToInt64(row["LoanCount"]));
                                htable.Add("@LoanDueAmount", Convert.ToInt64(row["LoanDueAmount"]));
                            }
                            htable.Add("@TDSAmount", Convert.ToInt64(row["TDSAmount"]));
                            htable.Add("@Professional_Tax", Convert.ToInt64(row["Professional_Tax"]));
                            htable.Add("@TotalDeduction", Convert.ToInt64(row["TotalDeduction"]));
                            htable.Add("@TotalAddition", Convert.ToInt64(row["TotalAdditions"]));
                            htable.Add("@NetSalary", Convert.ToInt64(row["NetSalary"]));
                            ds.Clear();
                            ds = objPayrollData.InsertPayslipReportData(htable);
                            ViewState["gridData"] = ds;
                            htable.Clear();

                            count="U";


                        }
                        else
                        {
                            htable.Clear();
                         
                            htable.Add("@tag", 'I');
                            htable.Add("@EmployeeName", Convert.ToString(row["EmployeeName"]));
                            htable.Add("@EmployeeCodeID", Convert.ToString(row["Employee_Code_Id"]));
                            htable.Add("@Designation", Convert.ToString(row["Designation"]));
                            htable.Add("@Gender", Convert.ToString(row["Gender"]));
                            htable.Add("@PayslipMonth", Convert.ToString(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(dt.Month)));
                            htable.Add("@year", Convert.ToString(dt.Year));
                            htable.Add("@Calender_Days", Convert.ToInt32(row["Calender_Days"]));
                            htable.Add("@PD", Convert.ToInt32(row["Present_Days"]));
                            htable.Add("@AD", Convert.ToInt32(row["Absent_Days"]));
                            htable.Add("@LD", Convert.ToInt32(row["Leave_Days"]));
                            htable.Add("@WOD", Convert.ToInt32(row["Weekly_OFF_Days"]));
                            htable.Add("@HD", Convert.ToInt32(row["Holiday_Days"]));
                            htable.Add("@LOPD", Convert.ToInt32(row["LossofPay_Days"]));
                            htable.Add("@TotalOT", Convert.ToString(row["TotalOTHrs"]));
                            htable.Add("@CTC", Convert.ToInt64((row["CostToCompany"])));
                            htable.Add("@BasicSalary", Convert.ToInt64(row["BasicSalary"]));
                            htable.Add("@DA", Convert.ToInt64(row["Dearness_Allowance"]));
                            htable.Add("@HRA", Convert.ToInt64(row["HouseRent_Allowance"]));
                            htable.Add("@EarnedAmount", Convert.ToInt64(row["EarnedAmount"]));
                            htable.Add("@CA", Convert.ToInt64(Convert.ToString(row["Conveyance_Allowance"]) == String.Empty ? "0": Convert.ToString(row["Conveyance_Allowance"])));
                            htable.Add("@MA", Convert.ToInt64(row["Medical_Allowance"]));
                            htable.Add("@CEA", Convert.ToInt64(row["Children_Education_Allowance"]));
                            htable.Add("@OA", Convert.ToInt64(row["OA"]));
                            htable.Add("@Tds_PolicyId", Convert.ToInt32(row["Tds_PolicyId"]));
                            htable.Add("@PF", Convert.ToInt64(Convert.ToString(row["ProvidentFund"]) == String.Empty ? "0" : Convert.ToString(row["ProvidentFund"])));
                            htable.Add("@ESI", Convert.ToInt64(Convert.ToString(row["ESI"])==String.Empty?"0": Convert.ToString(row["ESI"])));
                            if (Convert.ToString(row["LoanCount"]) == "")
                            {
                                htable.Add("@LoanCount", Convert.ToInt64(0));
                                htable.Add("@LoanDueAmount", Convert.ToInt64(0));
                            }
                            else
                            {
                                htable.Add("@LoanCount", Convert.ToInt64(row["LoanCount"]));
                                htable.Add("@LoanDueAmount", Convert.ToInt64(row["LoanDueAmount"]));
                            }
                            htable.Add("@TDSAmount", Convert.ToInt64(row["TDSAmount"]));
                            htable.Add("@Professional_Tax", Convert.ToInt64(row["Professional_Tax"]));
                            htable.Add("@TotalDeduction", Convert.ToInt64(row["TotalDeduction"]));
                            htable.Add("@TotalAddition", Convert.ToInt64(row["TotalAdditions"]));
                            htable.Add("@NetSalary", Convert.ToInt64(row["NetSalary"]));
                            ds.Clear();
                            ds = objPayrollData.InsertPayslipReportData(htable);
                            ViewState["gridData"] = ds;
                            htable.Clear();
                            count="I";
                        }
                        
                    }
                    if(count=="I")
                    {
                        base.MessagewithClose(rm.GetString("Alert_Payslipsavedsuccessfully", ci));
                    }
                    else
                    {
                        base.MessagewithClose(rm.GetString("Alert_PayslipUpdatesuccessfully", ci));
                    }

                }
                else
                {
                    base.MessagewithClose(rm.GetString("Alert_PayslipAlreadysaved", ci));
                }
                gvData.DataSource = (DataSet)ViewState["gridData"];
                gvData.DataBind();
               
            } 


        }
        catch (Exception Ex)
        {
            throw Ex;
        }
    }

    protected void lnkbtnGrid_Click(object sender, EventArgs e)
    {
        clearControls();
        GetAndSetFieldValues();
        dsEmp = GetDataset();

        ViewState["gridData"] = dsEmp;
        gvData.Visible = true;

        gvData.DataSource = ViewState["gridData"];
        gvData.DataBind();

        trSave.Visible = true;
    }

    private DataSet GetDataset()
    {
        DataSet dsEmp = new DataSet();
        if (ParenetLevelid == "") ParenetLevelid = "0";
        Hashtable empTable = new Hashtable();
        //Select Payroll Module Paarmeter
        empTable.Add("@EmployeeId", empId);
        empTable.Add("@EmployeeName", empName);
        empTable.Add("@LevelID", Level);
        empTable.Add("@employeeCategory", Convert.ToString(employeeCategory));
        empTable.Add("@employeeType", Convert.ToString(employeeType));
        empTable.Add("@UserGroupName", Convert.ToString(Session["UserGroupName"]));
        empTable.Add("@GradeLevel ", Convert.ToString(Session["GradeLevel"]));
        empTable.Add("@EmpSwipeCard", strSwipeCard);
        empTable.Add("@ParentId", Convert.ToInt16(ParenetLevelid));
        empTable.Add("@Fromdate1", strdtFromDate);
        empTable.Add("@Todate1", strdtToDate);
        empTable.Add("@DesignationID", Convert.ToInt32(ddlDesignation.SelectedValue));
        empTable.Add("@Gender ", Convert.ToString(ddlGender.SelectedValue));
        empTable.Add("@EmpAutoID", Convert.ToInt32(Session["EmpAutoID"]));
        dsEmp = objPayrollData.SelectEmployeePayrollReport(empTable);
        return dsEmp;

    }

    private void GetAndSetFieldValues()
    {
        strSwipeCard = Convert.ToString(txtEmployeeId.Text).Trim().Replace("'", "''");
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        strdtFromDate = txtFromDate.Text;
        strdtToDate = txtToDate.Text;
        strdtFromDate = objCommon.DateConvertion(gstrDateFormat, strdtFromDate);
        strdtToDate = objCommon.DateConvertion(gstrDateFormat, strdtToDate);
        if (strdtFromDate != string.Empty && strdtToDate != string.Empty)
        {
            dtFromDate1 = Convert.ToDateTime(strdtFromDate).Date;
            dtToDate1 = DateTime.Parse(strdtToDate);
            diff = dtToDate1.Subtract(dtFromDate1);
            day = diff.Days;
        }
        day = day + 1;
        if (day > 31)
        {
            base.Message("Selected Date range should not exceed 31 Days");
            return;
        }
        if (intIndividualUser >= 1)
        {
            empName = string.Empty;
            empId = Convert.ToString(Session["EmployeeCodeId"]);
        }
        else
        {
            empName = Convert.ToString(txtEmployeeName.Text);
            empId = Convert.ToString(txtEmployeeId.Text).Trim();
            Level = rptcommon.getNodes(Convert.ToInt16(Session["parentLevelId"]), Convert.ToString(Session["LevelRights"]));
        }
        if (Convert.ToInt32(ddlEmpCatagory.SelectedValue) != 0)
            employeeCategory = Convert.ToInt32(ddlEmpCatagory.SelectedValue);
        else
            employeeCategory = 0;
        if (Convert.ToInt32(ddlEmpType.SelectedValue) != 0)
            employeeType = Convert.ToInt32(ddlEmpType.SelectedValue);
        else
            employeeType = 0;
        //SelectedMonth = ddlMonth.SelectedValue;
        //SelectedYear = ddlYear.SelectedValue;
        ParenetLevelid = Convert.ToString(Session["parentLevelId"]);

    }

    protected void btnBack_Click(object sender, EventArgs e)
    {
        string strMsg;
        strMsg = "<script language='javascript'>";
        strMsg = strMsg + "parent.$('#myModalReport').modal('hide');";
        strMsg = strMsg + "</script>";
        Page.RegisterStartupScript("close report window", strMsg);
        return;
    }

    protected void btn_Export_Click(object sender, EventArgs e)
    {
        //DataSet dsEmp = new DataSet();

        //string Level = string.Empty;
        //string employeeName = string.Empty;
        //string empName = string.Empty;
        //string empId = string.Empty;
        //int shift;
        //try
        //{
        //    if (Page.IsValid == true)
        //    {
        //        string dtFrom = "", dtTo = "";
        //        if (txtFromDate.Text != "")
        //            dtFrom = strFromdate;
        //        if (txtToDate.Text != "")
        //            dtTo = strTodate;

        //        if (intIndividualUser >= 1)
        //        {
        //            empName = string.Empty;
        //            Level = string.Empty;
        //            empId = Convert.ToString(Session["EmployeeCodeId"]);
        //        }
        //        else
        //        {
        //            empName = Convert.ToString(txtEmployeeName.Text);
        //            empId = Convert.ToString(txtEmployeeId.Text).Trim();
        //            employeeName = this.txtEmployeeName.Text.Replace("'", "''");
        //            Level = rptcommon.getNodes(Convert.ToInt16(Session["parentLevelId"]), Convert.ToString(Session["LevelRights"]));
        //        }
        //        // dsEmp = rptEmp.SelectGeneralMonthlyAttendanceReport(dtFrom, dtTo, employeeName, Level, empId, Convert.ToInt16(ddlEmpCatagory.SelectedValue), Convert.ToInt16(ddlEmpType.SelectedValue), Convert.ToString(Session["UserGroupName"]), Convert.ToString(Session["GradeLevel"]), empId, Convert.ToInt16(Session["parentLevelId"]), Convert.ToInt16(ddlDesignation.SelectedValue), ddlGender.SelectedValue, Convert.ToInt32(Session["EmpAutoID"]));
        //        DataTable dtLevelName = new DataTable();
        //        if (Convert.ToInt16(Session["parentLevelId"]) != 0)
        //        {
        //            dtLevelName = rptEmp.getHeader(Convert.ToInt16(Session["parentLevelId"]));
        //        }
        //        if (dsEmp.Tables["Table"] == null || dsEmp.Tables["Table"].Rows.Count == 0)
        //        {
        //            Message(rm.GetString("Alert_Thereisnorecord", ci));
        //            return;
        //        }
        //        else
        //        {
        //            Session["Export_ExcelData"] = dsEmp;
        //            Response.Redirect("Excel_Export.aspx?ReportName=General Monthly&FrmDate=" + Convert.ToString(txtFromDate.Text) + "&toDate=" + Convert.ToString(txtToDate.Text) + "");
        //        }
        //    }
        //}
        //catch (Exception ex)
        //{
        //    Response.Write(ex);
        //}
    }
    #endregion
    private void clearControls()
    {
        ViewState["Payslip"] = null;
        gvData.DataSource = null;
        gvData.DataBind();
        gvData.Visible = false;
    }
 

    protected void gvData_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvData.PageIndex = e.NewPageIndex;
        gvData.DataBind();
    }

   

    protected void gvData_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        //int rowIndex = Convert.ToInt32(e.CommandArgument);

        //GridViewRow row = gvData.Rows[rowIndex];

        //Int64 Addtion = Convert.ToInt64((row.FindControl("lbl_TotalAddition") as Label).Text);

        //Int64 otherAllowance = Convert.ToInt64((row.FindControl("txtOtherAllowance") as TextBox).Text);

        //Int64 Total = Addtion + otherAllowance;

        //row.Cells[19].Text = Convert.ToString(Total);

    }


    protected void txtOtherAllowance_TextChanged(object sender, EventArgs e)
    {
        TextBox txt = sender as TextBox;
        txt.EnableViewState = true;
        Int64 TotalAddtion = 0;
        Int64 TotalDeduction = 0;
        Int64 prevOtherAllowance = 0;
        Int64 prevLoan = 0;
        string id = txt.ID;

        GridViewRow row = (GridViewRow)txt.Parent.Parent;
        //int RowIndex =row.RowIndex;

        //Total Addition Calculation
        Int64 Addtion = Convert.ToInt64((row.FindControl("lbl_TotalAddition") as Label).Text);

        Int64 otherAllowance = Convert.ToInt64((row.FindControl("txtOtherAllowance") as TextBox).Text==""?"0": (row.FindControl("txtOtherAllowance") as TextBox).Text);


        if(!IsPostBack)
        {
            prevOtherAllowance = 0;
            prevLoan = 0;
        }
        else
        {
            DataSet ds1 = (DataSet)ViewState["gridData"];
            prevOtherAllowance = Convert.ToInt64(ds1.Tables[0].Rows[row.RowIndex]["OA"]);
            prevLoan= Convert.ToInt64(ds1.Tables[0].Rows[row.RowIndex]["LoanDueAmount"]);
        }

        if(otherAllowance<prevOtherAllowance )
        {
            if(otherAllowance!=0)
            {
                TotalAddtion = Addtion - otherAllowance;
            }
            else
            {
                TotalAddtion = Addtion - prevOtherAllowance;
            } 
        }
        else
        {
            TotalAddtion = Addtion + otherAllowance;
        }

        // Total Deduction Calculation



        Int64 Dedcution = Convert.ToInt64((row.FindControl("lbl_Totaldeduction") as Label).Text);
        Int64 LoanDueAmount = Convert.ToInt64((row.FindControl("txtLoanDueAmount") as TextBox).Text==""?"0": (row.FindControl("txtLoanDueAmount") as TextBox).Text);
        if (LoanDueAmount<prevLoan)
        {
            if (LoanDueAmount != 0)
            {
                TotalDeduction = Dedcution - LoanDueAmount;
            }
            else
            {
                prevLoan = Dedcution - LoanDueAmount;
            }
           
        }
        else
        {
            TotalDeduction = Dedcution + LoanDueAmount;
        }
        // Total net Salary
        Int64 TotalNetSalary = TotalAddtion - TotalDeduction;



        row.Cells[19].Text = Convert.ToString(TotalAddtion);

        row.Cells[26].Text = Convert.ToString(TotalDeduction);

        row.Cells[27].Text = Convert.ToString(TotalNetSalary);


        DataSet ds =(DataSet) ViewState["gridData"]; 

        ds.Tables[0].Rows[row.RowIndex]["OA"] = otherAllowance;

        ds.Tables[0].Rows[row.RowIndex]["LoanDueAmount"] = LoanDueAmount;

        ds.Tables[0].Rows[row.RowIndex]["TotalAdditions"] = TotalAddtion;

        ds.Tables[0].Rows[row.RowIndex]["TotalDeduction"] = TotalDeduction;

        ds.Tables[0].Rows[row.RowIndex]["NetSalary"] = TotalNetSalary;

        ViewState["gridData"] = ds;


        BindData();
       


    }

    private void BindData()
    {
        if(ViewState["gridData"]!=null)
        {
            gvData.DataSource = ViewState["gridData"];
            gvData.DataBind();
        }
    }
}
