#region using
using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using Sapphire.Ohu.BaseFramework.GlobalizationLocalization;
using Sapphire.Ohu.BaseFramework.Utilities;
using Sapphire.Ohu.BusinessEntity.Application.MasterBE;
using Sapphire.Ohu.BusinessEntity.Business.Hrm.EmployeeBE;
using Sapphire.Ohu.BusinessEntity.Framework.BaseFrameworkBE;
using Sapphire.Ohu.BusinessEntity.Framework.UtilityBE;
using Sapphire.Ohu.BusinessLogic.Business.Hrm.EmployeeBL;
using Sapphire.Ohu.Web.Helper;
using Sapphire.Ohu.Web.PageController;
using Sapphire.Ohu.Web.SessionHelper;
using Sapphire.Vidyalaya.BusinessEntity.Business.StudentManagementBE;
using Sapphire.Vidyalaya.BusinessLogic.Business.StudentManagement.StudentBL;
using System.IO;
using System.Drawing;
using System.Web;
using System.Linq;
using Sapphire.Ohu.BaseFramework.Exceptions;
using System.Text;
using System.Data;
using System.Configuration;
using Sapphire.Vidyalaya.BusinessLogic.Business.Common.CommonBL;

#endregion

public partial class Pages_StudentManagement_StudentSearch : PageController
{

    #region Enums
    #endregion

    #region Constants
    private int RowCount = 0;
    private bool IsActivateUniqueId = false;
    private string IdLabel = "";
    private string Suidlabel = "";
    /// <summary>
    /// Page Level Constants
    /// </summary>

    #endregion

    #region Service Client
    /// <summary>
    /// Method To Create Instance For Employee Management Service Contract
    /// </summary>
    /// 

    private StudentService StudentServiceClient
    {
        get
        {
            return new StudentService();
        }
    }

    ControllHelper ControllHelperObject = new ControllHelper();

    #endregion

    #region Private Members

    /// <summary>
    /// Page Level Private Members
    /// </summary>

    #endregion

    #region Events


    /// <summary>
    /// Function To Handle Page Load Event
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            GetPermission();
            // Checks If The Page Is Posted Back
            IsActivateUniqueId = Convert.ToBoolean((ConfigurationHelper.GetUserConfigurationValue("Student.IsActivateSUId")));
            Suidlabel = "SU Id";
            IdLabel = ConfigurationHelper.GetUserConfigurationValue("Common.IDNoLabel");
            IDNoLabel.Text = IdLabel;
            StudentSearchGridView.Columns[6].HeaderText = IdLabel;

            if (IsActivateUniqueId == true)
            {
                SUIdDiv.Visible = true;
                this.StudentSearchGridView.Columns[5].Visible = true;
            }
            else
            {
                SUIdDiv.Visible = false;
                this.StudentSearchGridView.Columns[5].Visible = false;
            }

            if (!IsPostBack)
            {
                RedirectToMigration();
                StudentManagementSession.AllStudentList = null;

                base.SetScreenTitle(StudentManagementScreenId.Student.StudentSearch);
                // Function To Handle Page Load Activities
                PageLoadActivities();
                BackPage();

            }
            // Function To Handle Page Post Back Activities
            PagePostBackActivities();
            GetPermission();

        }
        catch (Exception ex)
        {
            ExceptionHelper.HandleException(ex, ExceptionPolicyEnum.UI_Policy);
            MessageBox.Show("Error on loading data", MessageType.Error);
        }
    }

    private void BackPage()
    {
        if (StudentManagementSession.StudentSearchBack != null)
        {
            if (SecuritySession.UserProfile.PageName == "Student Search")
            {
                IDNoTextBox.Text = StudentManagementSession.StudentSearchBack.Code;

                FirstNameSearchTextBox.Text = StudentManagementSession.StudentSearchBack.FirstName;
                MiddleNameSearchTextBox.Text = StudentManagementSession.StudentSearchBack.MiddleName;
                LastNameTextBox.Text = StudentManagementSession.StudentSearchBack.LastName;
                if (StudentManagementSession.StudentSearchBack.RollNo.ToString() != "0")
                    RollNoTextBox.Text = StudentManagementSession.StudentSearchBack.RollNo.ToString();
                ClassDropDownList.SelectedValue = StudentManagementSession.StudentSearchBack.ClassId.ToString();
                ClassDropDownList_SelectedIndexChanged(null, null);
                DivisionDropDownList.SelectedValue = StudentManagementSession.StudentSearchBack.DivisionId.ToString();
                StatusDropDownList.SelectedIndex = 1;
                OrderByDropDownList.SelectedValue = StudentManagementSession.StudentSearchBack.OrderBy.ToString();
                ShowWithPhotoCheckBox.Checked = StudentManagementSession.StudentSearchBack.IsGeneral;
                IDNoTextBox.Focus();

                GetAvailableStudentData();
                AvailableStudentDataBind();
            }
        }
    }


    /// <summary>
    /// Function To Set Tab Index For Controls
    /// </summary>
    private void SetTabIndex()
    {
        short TabIndex = 1;
        IDNoTextBox.Focus();
        IDNoTextBox.TabIndex = ++TabIndex;
        FirstNameSearchTextBox.TabIndex = ++TabIndex;
        MiddleNameSearchTextBox.TabIndex = ++TabIndex;
        MiddleNameSearchTextBox.TabIndex = ++TabIndex;
        LastNameTextBox.TabIndex = ++TabIndex;
        DepartmentDropDownList.TabIndex = ++TabIndex;
        ClassDropDownList.TabIndex = ++TabIndex;
        DivisionDropDownList.TabIndex = ++TabIndex;
        RollNoTextBox.TabIndex = ++TabIndex;
        StatusDropDownList.TabIndex = ++TabIndex;
        ClassStatusDropDownList.TabIndex = ++TabIndex;
        OrderByDropDownList.TabIndex = ++TabIndex;
        SUIdTextBox.TabIndex = ++TabIndex;
        ContactNoTextBox.TabIndex = ++TabIndex;
        ShowWithPhotoCheckBox.TabIndex = ++TabIndex;
        SearchButton.TabIndex = ++TabIndex;
        ClearButton.TabIndex = ++TabIndex;
        AddnewButton.TabIndex = ++TabIndex;
        foreach (GridViewRow dr in StudentSearchGridView.Rows)
        {
            LinkButton EditLinkButton = (LinkButton)(dr.FindControl("EditLinkButton"));
            LinkButton StudentAllLinkButton = (LinkButton)(dr.FindControl("StudentAllLinkButton"));
            LinkButton InDetailLinkButton = (LinkButton)(dr.FindControl("InDetailLinkButton"));
            LinkButton ProfileLinkButton = (LinkButton)(dr.FindControl("ProfileLinkButton"));
            LinkButton ViewLinkButton = (LinkButton)(dr.FindControl("ViewLinkButton"));
            EditLinkButton.TabIndex = ++TabIndex;
            StudentAllLinkButton.TabIndex = ++TabIndex;
            InDetailLinkButton.TabIndex = ++TabIndex;
            ProfileLinkButton.TabIndex = ++TabIndex;
            ViewLinkButton.TabIndex = ++TabIndex;
        }

    }
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ClearSearchControls_Click(object sender, EventArgs e)
    {
        try
        {
            ClearSession();
            ClearControls();
            IDNoTextBox.Focus();
            LoadSearchPanelDropDownLists();
        }
        catch (Exception ex)
        {
            ExceptionHelper.HandleException(ex, ExceptionPolicyEnum.UI_Policy);
            MessageBox.Show("Error on loading data", MessageType.Error);
        }
    }

    /// <summary>
    /// Function To Handle Search Button Click Event
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void SearchButton_Click(object sender, EventArgs e)
    {
        try
        {
            //Changes for Mantis Id : 0034109 By Hemali
            string HostedAs = ConfigurationManager.AppSettings["HostedAs"].ToString().ToLower();
            if (HostedAs == "online" || HostedAs == "portal")
            {
                string sql_string = "Select case when (ISNULL(NoOfStudent,0)+ISNULL(StudentExtraCap,0))<([sSetup].[fStudentCapGet](" + SecuritySession.UserProfile.OrgGroupBatchId + ")) then -111 " +
                    "else  1 end from sSetup.tOrgGroupSetting Where OrgGroupId=" + SecuritySession.UserProfile.OrgGroupId;
                CommonFunctions cf = new CommonFunctions();
                DataSet ds = cf.GetDataset(sql_string);
                if ((ds != null || ds.Tables[0].Rows.Count > 0) && ds.Tables[0].Rows[0][0].ToString() == "-111")
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "alertMessage", "showmodalpopup();", true);
                }
            }
            GetAvailableStudentData();
            AvailableStudentDataBind();
        }
        catch (Exception ex)
        {
            ExceptionHelper.HandleException(ex, ExceptionPolicyEnum.UI_Policy);
            MessageBox.Show("Error on loading data", MessageType.Error);
        }
    }

    private void GetAvailableStudentData()
    {

        //List<DataParameter> dp = new List<DataParameter>();
        //DataParameter d;

        //d = new DataParameter { Name = "@Id", Value = "1", DataType = System.Data.DbType.Int16 };
        //dp.Add(d);

        //d = new DataParameter { Name = "1", Value = "A", DataType = System.Data.DbType.String };
        //dp.Add(d);

        //CommonFunctions cf = new CommonFunctions();
        //Dataset ds = cf.GetDatasetFromSp("sCommon.pStudentGet", dp);


        Student StudentData = new Student();
        //if(!string.IsNullOrEmpty(NumberTextBox.Text))
        //    StudentData.Number = Int64.Parse(NumberTextBox.Text.ToString());
        StudentData.Code = IDNoTextBox.Text.ToString();
        if (!string.IsNullOrEmpty(RollNoTextBox.Text))
            StudentData.SearchRollNo = Int32.Parse(RollNoTextBox.Text.ToString());
        StudentData.FirstName = FirstNameSearchTextBox.Text.ToString();
        StudentData.MiddleName = MiddleNameSearchTextBox.Text.ToString();
        StudentData.LastName = LastNameTextBox.Text.ToString();
        if (ClassDropDownList.SelectedIndex > 0)
            StudentData.ClassId = int.Parse(ClassDropDownList.SelectedValue);
        else
            StudentData.ClassId = 0;
        if (DivisionDropDownList.SelectedIndex > 0)
            StudentData.DivisionId = int.Parse(DivisionDropDownList.SelectedValue);
        else
            StudentData.DivisionId = 0;
        if (StatusDropDownList.SelectedIndex > 0)
            StudentData.StatusId = int.Parse(StatusDropDownList.SelectedValue);
        else
            StudentData.StatusId = 0;
        StudentData.OrderBy = Int32.Parse(OrderByDropDownList.SelectedValue.ToString());
        StudentData.OrgId = SecuritySession.UserProfile.OrgId;
        StudentData.BatchId = SecuritySession.UserProfile.BatchId;
        StudentData.OrgGroupBatchId = SecuritySession.UserProfile.OrgGroupBatchId;
        if (DepartmentDropDownList.SelectedIndex > 0)
        {
            StudentData.DepartmentId = int.Parse(DepartmentDropDownList.SelectedValue);
        }
        else
        {
            StudentData.DepartmentId = SecuritySession.UserProfile.DepartmentId;
        }
        if (!string.IsNullOrEmpty(SUIdTextBox.Text))
            StudentData.SUId = SUIdTextBox.Text;

        StudentData.UserId = SecuritySession.UserProfile.UserId;

        if (ClassStatusDropDownList.SelectedIndex > 0)
        {
            StudentData.ClassStatusId = Int16.Parse(ClassStatusDropDownList.SelectedValue.ToString());
        }
        else
        {
            StudentData.ClassStatusId = 0;
        }

        StudentData.ContactNo = ContactNoTextBox.Text;

        if (ShowWithPhotoCheckBox.Checked)
        {
            StudentManagementSession.AllStudentList = StudentServiceClient.StudentListWithPhoto(StudentData);
        }
        else
        {
            StudentManagementSession.AllStudentList = LoadData(StudentData);
        }
    }

    private List<Student> LoadData(Student StudentData)
    {
        return StudentServiceClient.StudentSearchGet(StudentData);
    }

    protected void LinkButton_Click(object sender, EventArgs e)
    {
        try
        {
            Session["AllowCreate"] = null;
            Student StudentData = new Student();

            int RowIndex = Convert.ToInt32(((LinkButton)sender).CommandArgument);
            GridViewRow row = StudentSearchGridView.Rows[RowIndex];
            Int64 Id = Int64.Parse(StudentSearchGridView.DataKeys[RowIndex].Values["Id"].ToString());
            StudentData.Id = Id;
            GetPageDetail();
            StudentManagementSession.StudentData = StudentData;
            StudentManagementSession.StudentList = null; //Add For Mantis Id : 0030713 By Hemali
            Response.Redirect("~/Pages/StudentManagement/Student.aspx");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString(), MessageType.Error);
        }
    }

    protected void ProfileLinkButton_Click(object sender, EventArgs e)
    {
        try
        {
            Student StudentData = new Student();
            int RowIndex = Convert.ToInt32(((LinkButton)sender).CommandArgument);
            GridViewRow row = StudentSearchGridView.Rows[RowIndex];
            Int64 Id = Int64.Parse(StudentSearchGridView.DataKeys[RowIndex].Values["Id"].ToString());

            StudentData.StudentId = Id;
            StudentData.BatchId = SecuritySession.UserProfile.BatchId;
            StudentData.OrgId = SecuritySession.UserProfile.OrgId;
            StudentData.OrgGroupBatchId = SecuritySession.UserProfile.OrgGroupBatchId;
            StudentData.UserSourceTypeId = 2003;
            GetPageDetail();
            StudentManagementSession.StudentFullProfile = StudentData;
            Response.Redirect("~/Pages/StudentManagement/StudentFullProfile.aspx?ScreenSource=Search");
        }
        catch (Exception ex)
        {
            ExceptionHelper.HandleException(ex, ExceptionPolicyEnum.UI_Policy);
            MessageBox.Show("Error on loading data", MessageType.Error);
        }
    }

    protected void StudentAllLinkButton_Click(object sender, EventArgs e)
    {
        try
        {
            Session["AllowCreate"] = null;
            Student StudentData = new Student();

            int RowIndex = Convert.ToInt32(((LinkButton)sender).CommandArgument);
            GridViewRow row = StudentSearchGridView.Rows[RowIndex];
            Int64 Id = Int64.Parse(StudentSearchGridView.DataKeys[RowIndex].Values["Id"].ToString());
            StudentData.Id = Id;
            GetPageDetail();
            StudentManagementSession.StudentData = StudentData;
            Response.Redirect("~/Pages/StudentManagement/StudentAllDetails.aspx");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString(), MessageType.Error);
        }
    }

    protected void InDetailLinkButton_Click(object sender, EventArgs e)
    {
        try
        {
            Student StudentData = new Student();
            int RowIndex = Convert.ToInt32(((LinkButton)sender).CommandArgument);
            GridViewRow row = StudentSearchGridView.Rows[RowIndex];
            Int64 Id = Int64.Parse(StudentSearchGridView.DataKeys[RowIndex].Values["Id"].ToString());
            StudentData.StudentId = Id;
            StudentData.BatchId = SecuritySession.UserProfile.BatchId;
            StudentData.UserSourceTypeId = 2003;
            GetPageDetail();
            StudentManagementSession.StudentFullProfile = StudentData;

            ContextData cd = new ContextData();
            cd.StudentId = Id;
            cd.BatchId = SecuritySession.UserProfile.BatchId;
            SecuritySession.ContextData = cd;

            Response.Redirect("~/Pages/StudentManagement/StudentFullProfile.aspx?ScreenSource=Search");
        }
        catch (Exception ex)
        {
            ExceptionHelper.HandleException(ex, ExceptionPolicyEnum.UI_Policy);
            MessageBox.Show("Error on loading data", MessageType.Error);
        }
    }

    private void GetPageDetail()
    {
        StudentManagementSession.StudentSearchBack = null;
        Student StudentDetailData = new Student();
        try
        {
            StudentDetailData.Code = IDNoTextBox.Text;
            StudentDetailData.SUId = SUIdTextBox.Text;
            StudentDetailData.FirstName = FirstNameSearchTextBox.Text;
            StudentDetailData.LastName = LastNameTextBox.Text;
            if (!string.IsNullOrEmpty(RollNoTextBox.Text))
                StudentDetailData.RollNo = Int32.Parse(RollNoTextBox.Text.ToString());
            StudentDetailData.ClassId = Int32.Parse(ClassDropDownList.SelectedValue.ToString());
            StudentDetailData.DivisionId = Int32.Parse(DivisionDropDownList.SelectedValue.ToString());
            StudentDetailData.StatusId = Int32.Parse(StatusDropDownList.SelectedValue.ToString());
            StudentDetailData.OrderBy = Int32.Parse(OrderByDropDownList.SelectedValue.ToString());
            StudentDetailData.IsGeneral = ShowWithPhotoCheckBox.Checked;

            StudentManagementSession.StudentSearchBack = StudentDetailData;
            SecuritySession.UserProfile.PageName = "Student Search";
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString(), MessageType.Error);
        }
    }

    #endregion

    #region Template Methods

    /// <summary>
    /// Function To Clear Screen Controls
    /// </summary>
    private void ClearControls()
    {
        FirstNameSearchTextBox.Text = "*";
        MiddleNameSearchTextBox.Text = "*";
        LastNameTextBox.Text = "*";
        //NumberTextBox.Text = string.Empty;
        DepartmentDropDownList.SelectedIndex = 0;
        IDNoTextBox.Text = "*";
        RollNoTextBox.Text = string.Empty;
        ClassDropDownList.SelectedIndex = 0;
        DivisionDropDownList.SelectedIndex = 0;
        StatusDropDownList.SelectedIndex = 1;
        OrderByDropDownList.SelectedValue = "1";
        ShowWithPhotoCheckBox.Checked = false;
        SUIdTextBox.Text = string.Empty;
        ContactNoTextBox.Text = string.Empty;
    }

    /// <summary>
    /// Function To Clear Session Variables Local To The Screen
    /// </summary>
    /// <remarks>
    /// </remarks>
    private void ClearSession()
    {
        StudentManagementSession.AllStudentList = null;
        StudentManagementSession.StudentSearchBack = null;
    }

    /// <summary>
    /// Function To Register Events For Base Buttons
    /// </summary>
    private void RegisterBaseButtonEvents()
    {
        base.SaveButton.Visible = false;
        base.EditButton.Visible = false;
        base.DeleteButton.Visible = false;
        base.PrintButton.Visible = false;
        base.ClearButton.Visible = false;
    }

    protected void AddnewButtonControls_Click(object sender, EventArgs e)
    {
        try
        {
            ClearControls();
            ClearSession();
            StudentManagementSession.StudentData = null;
            StudentManagementSession.AdmissionDetailsData = null;
            Session["AllowCreate"] = null;
            Response.Redirect("~/Pages/StudentManagement/Student.aspx");
        }
        catch (Exception ex)
        {
            ExceptionHelper.HandleException(ex, ExceptionPolicyEnum.UI_Policy);
            MessageBox.Show("Error on loading data", MessageType.Error);
        }
    }

    /// <summary>
    /// Function To Load DropDownLists
    /// </summary>

    private void LoadSearchPanelDropDownLists()
    {
        StaticDataHelper StaticDataHelperObject = new StaticDataHelper();
        StaticDataHelperObject.FillStudentStatusDropDownList(StatusDropDownList, true);
        StaticDataHelperObject.FillStudentStatusDropDownList(ClassStatusDropDownList, true);

        StatusDropDownList.SelectedValue = "1";
        string SQL_String = string.Empty;

        ListItem li = new ListItem("- ALL -", "0");
        DivisionDropDownList.Items.Clear();
        DivisionDropDownList.Items.Insert(0, li);
        ClassDropDownList.Items.Clear();
        ClassDropDownList.Items.Insert(0, li);


        StringBuilder SB_SQL_String = new StringBuilder(10000);
        //SB_SQL_String = string.Empty;
        int OrgId = SecuritySession.UserProfile.OrgId;


        SB_SQL_String.Append("Select DISTINCT Cm.Id,Cm.Title,CM.OrderIndex from sSetup.tClassMaster CM INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id INNER JOIN sSetup.tBatchClass BC ON BC.ClassId = CM.Id INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id Where BC.BatchId = @BatchId AND DM.OrgId =@OrgId AND U.SourceTypeId=2005 AND U.UserId=@UserId ORDER BY CM.OrderIndex");
        //SB_SQL_String.Append("Select DISTINCT Cm.Id,Cm.Title,CM.OrderIndex from sSetup.tClassMaster CM INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id INNER JOIN sSetup.tBatchClass BC ON BC.ClassId = CM.Id INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id Where BC.BatchId = " + SecuritySession.UserProfile.BatchId + " AND DM.OrgId =" + OrgId + " AND U.SourceTypeId=2005 AND U.UserId= " + SecuritySession.UserProfile.UserId + "");
        //SB_SQL_String = "SELECT Id, Title FROM sSetup.vDepartment where IsObsolete = 0 AND OrgId=@OrgId AND UserId = @UserId AND   ( Id = @DepartmentId OR @DepartmentId = 0 ) ORDER BY Title";
        //SQL_String = SQL_String + " select Id,Title from sExamination.tSetupGroupMaster where MainTypeId = @rMainTypeId and OrgId = @rOrgId order by OrderIndex";
        SQLConnectionFunction objC = new SQLConnectionFunction();
        DataSet dsFillDrp = new DataSet();
        dsFillDrp = objC.QueryDataReader(SB_SQL_String.ToString(),
               objC.GetSqlParam("@BatchId", SqlDbType.Int, 8, SecuritySession.UserProfile.BatchId.ToString()),
               objC.GetSqlParam("@OrgId", SqlDbType.Int, 8, OrgId.ToString()),
               objC.GetSqlParam("@UserId", SqlDbType.VarChar, 20, SecuritySession.UserProfile.UserId.ToString())
               );

        if (dsFillDrp.Tables[0].Rows.Count > 0)
        {
            ClassDropDownList.DataSource = dsFillDrp.Tables[0];
            ClassDropDownList.DataValueField = "Id";
            ClassDropDownList.DataTextField = "Title";
            ClassDropDownList.DataBind();
            ListItem li1 = new ListItem();
            li1.Value = "-1";
            li1.Text = "- ALL -";
            ClassDropDownList.Items.Insert(0, li1);
            ClassDropDownList.SelectedIndex = 0;

        }


        StringBuilder SB_SQL_String1 = new StringBuilder(10000);
        //SB_SQL_String = "";
        // StringBuilder SB_SQL_String = new StringBuilder(10000);
        // SQL_String = string.Empty;

        //SB_SQL_String1.Append("SELECT Id, Title FROM sSetup.vDepartment where IsObsolete = 0 AND OrgId=@OrgId AND UserId = @UserId AND   ( Id = @DepartmentId OR @DepartmentId = 0 ) ORDER BY Title");
        SB_SQL_String1.Append("SELECT DM.Id, DM.Title FROM sSetup.tDepartmentMaster DM INNER JOIN sSecurity.tUserAccess UA ON DM.Id = UA.SourceId AND UA.SourceTypeId = 2017 where DM.IsObsolete = 0 AND DM.OrgId=@OrgId AND UA.UserId = @UserId AND   ( DM.Id = @DepartmentId OR @DepartmentId = 0 ) Order By DM.OrderIndex");

        //SB_SQL_String = "SELECT Id, Title FROM sSetup.vDepartment where IsObsolete = 0 AND OrgId=@OrgId AND UserId = @UserId AND   ( Id = @DepartmentId OR @DepartmentId = 0 ) ORDER BY Title";
        //SQL_String = SQL_String + " select Id,Title from sExamination.tSetupGroupMaster where MainTypeId = @rMainTypeId and OrgId = @rOrgId order by OrderIndex";
        //SQLConnectionFunction objC = new SQLConnectionFunction();
        // DataSet dsFillDrp = new DataSet();
        dsFillDrp = objC.QueryDataReader(SB_SQL_String1.ToString(),
               objC.GetSqlParam("@OrgId", SqlDbType.Int, 8, SecuritySession.UserProfile.OrgId.ToString()),
               objC.GetSqlParam("@UserId", SqlDbType.BigInt, 16, SecuritySession.UserProfile.UserId.ToString()),
               objC.GetSqlParam("@DepartmentId", SqlDbType.Int, 8, SecuritySession.UserProfile.DepartmentId.ToString())
               );

        if (dsFillDrp.Tables[0].Rows.Count > 0)
        {
            DepartmentDropDownList.DataSource = dsFillDrp.Tables[0];
            DepartmentDropDownList.DataValueField = "Id";
            DepartmentDropDownList.DataTextField = "Title";
            DepartmentDropDownList.DataBind();
            ListItem li2 = new ListItem();
            li2.Value = "-1";
            li2.Text = "- ALL -";
            DepartmentDropDownList.Items.Insert(0, li2);
            DepartmentDropDownList.SelectedIndex = 0;

        }
    }

    //private void LoadSearchPanelDropDownLists()
    //{
    //    //Function To Load Type DropDownList
    //    StaticDataHelper StaticDataHelperObject = new StaticDataHelper();
    //    StaticDataHelperObject.FillStudentStatusDropDownList(StatusDropDownList, true);
    //    string SQL_String = string.Empty;

    //    ListItem li = new ListItem("- ALL -", "0");
    //    DivisionDropDownList.Items.Clear();
    //    DivisionDropDownList.Items.Insert(0, li);
    //    ClassDropDownList.Items.Clear();
    //    ClassDropDownList.Items.Insert(0, li);

    //    int OrgId = SecuritySession.UserProfile.OrgId;
    //    //int BatchId = SecuritySession.UserProfile.BatchId;

    //    //string AttendanceEntryBasedOn = (ConfigurationHelper.GetUserConfigurationValue("Attendance.AttendanceEntryBasedOn"));
    //    //if (SecuritySession.UserProfile.UserSourceTypeId == 95)
    //    //{
    //    //    if (AttendanceEntryBasedOn == "Class Teacher")
    //    //    {
    //    //        SQL_String = "SELECT DISTINCT Cm.Id AS ClassId, CM.DisplayTitle AS ClassTitle  FROM sSetup.tClassMaster CM INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id WHERE DM.InchargeemployeeID=" + SecuritySession.UserProfile.UserSourceId + " AND CM.OrgId=" + OrgId;
    //    //        ControllHelperObject.LoadDropDownList(ClassDropDownList, SQL_String, "ClassId", "ClassTitle", true);
    //    //    }
    //    //    else if (AttendanceEntryBasedOn == "Academic Setup")
    //    //    {
    //    //        SQL_String = "SELECT DISTINCT ClassId, ClassTitle,ClassOrderIndex FROM sAcademic.vTeacherSubjectDivision WHERE EmployeeId=" + SecuritySession.UserProfile.UserSourceId + " AND OrgId=" + OrgId + " ORDER BY ClassOrderIndex";
    //    //        ControllHelperObject.LoadDropDownList(ClassDropDownList, SQL_String, "ClassId", "ClassTitle", true);
    //    //    }
    //    //    else if (AttendanceEntryBasedOn == "User Access")
    //    //    {
    //    SQL_String = "Select DISTINCT Cm.Id,Cm.Title,CM.OrderIndex from sSetup.tClassMaster CM INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id INNER JOIN sSetup.tBatchClass BC ON BC.ClassId = CM.Id " +
    //                         " INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id Where BC.BatchId = " + SecuritySession.UserProfile.BatchId + " AND DM.OrgId =" + OrgId + " AND U.SourceTypeId=2005 AND U.UserId = " + SecuritySession.UserProfile.UserId;
    //    ControllHelperObject.LoadDropDownList(ClassDropDownList, SQL_String, "Id", "Title", true);
    //    //    }
    //    //}
    //    //else
    //    //{
    //    //    SQL_String = string.Empty;
    //    //    SQL_String = "SELECT ClassId, ClassName FROM sSetup.vBatchClass WHERE IsObsolete = 0  AND BatchId=" + BatchId + " ORDER BY OrderIndex";
    //    //    ControllHelperObject.LoadDropDownList(ClassDropDownList, SQL_String, "ClassId", "ClassName", true);
    //    //}

    //    //SQL_String = "SELECT ClassId, ClassName FROM sSetup.vBatchClass WHERE IsObsolete = 0  AND BatchId=" + SecuritySession.UserProfile.BatchId + " ORDER BY OrderIndex";
    //    //ControllHelperObject.LoadDropDownList(ClassDropDownList, SQL_String, "ClassId", "ClassName", true);
    // LoadDropDownListValues(ClassDropDownList, "sSetup.vBatchClass", "ClassId", "ClassName", " IsObsolete = 0  AND BatchId=" + SecuritySession.UserProfile.BatchId, 0, SortOrder.SortCustomAscending, "OrderIndex", true);

    //    //  SQL_String = "SELECT Id, Title FROM sStudent.tStatusMaster WHERE IsObsolete = 0 ORDER BY Title";
    //    //ControllHelperObject.LoadDropDownList(StatusDropDownList, SQL_String, "Id", "Title", true);
    //    //LoadDropDownListValues(StatusDropDownList, "sStudent.tStatusMaster", "Id", "Title", " IsObsolete = 0 ", 0, SortOrder.SortByFieldNameAscending, "", true);
    //    StatusDropDownList.SelectedIndex = 1;

    //    SQL_String = string.Empty;
    //    SQL_String = "SELECT Id, Title FROM sSetup.vDepartment WHERE IsObsolete = 0  AND OrgId=" + SecuritySession.UserProfile.OrgId + " AND UserId = " + SecuritySession.UserProfile.UserId + " AND   ( Id = " + SecuritySession.UserProfile.DepartmentId + " OR " + SecuritySession.UserProfile.DepartmentId + " = 0 ) ORDER BY Title";
    //    ControllHelperObject.LoadDropDownList(DepartmentDropDownList, SQL_String, "Id", "Title", true);
    //    //string Condition = string.Empty;
    //    //Condition = "IsObsolete = 0  AND OrgId=" + SecuritySession.UserProfile.OrgId + " AND UserId = " + SecuritySession.UserProfile.UserId + " AND   ( Id = " + SecuritySession.UserProfile.DepartmentId + " OR " + SecuritySession.UserProfile.DepartmentId + " = 0 )";
    //    //LoadDropDownListValues(DepartmentDropDownList, "sSetup.vDepartment", "Id", "Title", Condition, 0, SortOrder.SortByFieldNameAscending, "", true);

    //}
    protected void DepartmentDropDownList_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            string SQL_String = string.Empty;

            if (DepartmentDropDownList.SelectedIndex > 0)
            {
                StringBuilder SB_SQL_String = new StringBuilder(10000);
                int OrgId = SecuritySession.UserProfile.OrgId;
                int DepartmentId = int.Parse(DepartmentDropDownList.SelectedValue);

                SB_SQL_String.Append("Select DISTINCT Cm.Id,Cm.Title,CM.OrderIndex from sSetup.tClassMaster CM INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id" +
                                      " INNER JOIN sSetup.tBatchClass BC ON BC.ClassId = CM.Id INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id Where DM.OrgId=@OrgId AND CM.DepartmentId=@DepartmentId AND U.SourceTypeId=2005 AND U.UserId=@UserId AND BC.BatchId=@BatchId");

                SQLConnectionFunction objC = new SQLConnectionFunction();
                DataSet dsFillDrp = new DataSet();
                dsFillDrp = objC.QueryDataReader(SB_SQL_String.ToString(),
                       objC.GetSqlParam("@OrgId", SqlDbType.Int, 8, OrgId.ToString()),
                       objC.GetSqlParam("@DepartmentId", SqlDbType.Int, 8, DepartmentId.ToString()),
                       objC.GetSqlParam("@UserId", SqlDbType.VarChar, 20, SecuritySession.UserProfile.UserId.ToString()),
                       objC.GetSqlParam("@BatchId", SqlDbType.Int, 8, SecuritySession.UserProfile.BatchId.ToString())
                       );

                if (dsFillDrp.Tables[0].Rows.Count > 0)
                {
                    ClassDropDownList.DataSource = dsFillDrp.Tables[0];
                    ClassDropDownList.DataValueField = "Id";
                    ClassDropDownList.DataTextField = "Title";
                    ClassDropDownList.DataBind();
                    ListItem li1 = new ListItem();
                    li1.Value = "-1";
                    li1.Text = "- ALL -";
                    ClassDropDownList.Items.Insert(0, li1);
                    ClassDropDownList.SelectedIndex = 0;

                }
                else
                {
                    ClassDropDownList.Items.Clear();
                    ListItem li1 = new ListItem();
                    li1.Value = "-1";
                    li1.Text = "- ALL -";
                    ClassDropDownList.Items.Insert(0, li1);
                    ClassDropDownList.SelectedIndex = 0;
                }

            }
            else
            {
                StringBuilder SB_SQL_String = new StringBuilder(10000);
                ListItem li = new ListItem("- ALL -", "0");

                int OrgId = SecuritySession.UserProfile.OrgId;

                SB_SQL_String.Append("Select DISTINCT Cm.Id,Cm.Title,CM.OrderIndex from sSetup.tClassMaster CM INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id" +
                                      " INNER JOIN sSetup.tBatchClass BC ON BC.ClassId = CM.Id INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id Where DM.OrgId=@OrgId AND U.SourceTypeId=2005 AND U.UserId = @UserId AND BC.BatchId = @BatchId");

                SQLConnectionFunction objC = new SQLConnectionFunction();
                DataSet dsFillDrp = new DataSet();
                dsFillDrp = objC.QueryDataReader(SB_SQL_String.ToString(),
                       objC.GetSqlParam("@OrgId", SqlDbType.Int, 8, OrgId.ToString()),
                        objC.GetSqlParam("@BatchId", SqlDbType.Int, 8, SecuritySession.UserProfile.BatchId.ToString()),
                       objC.GetSqlParam("@UserId", SqlDbType.VarChar, 20, SecuritySession.UserProfile.UserId.ToString())
                       );
                if (dsFillDrp.Tables[0].Rows.Count > 0)
                {
                    ClassDropDownList.DataSource = dsFillDrp.Tables[0];
                    ClassDropDownList.DataValueField = "Id";
                    ClassDropDownList.DataTextField = "Title";
                    ClassDropDownList.DataBind();
                    ListItem li1 = new ListItem();
                    li1.Value = "-1";
                    li1.Text = "- ALL -";
                    ClassDropDownList.Items.Insert(0, li1);
                    ClassDropDownList.SelectedIndex = 0;

                }

                DivisionDropDownList.Items.Clear();
                DivisionDropDownList.Items.Insert(0, li);
            }
            DepartmentDropDownList.Focus();
        }
        catch (Exception ex)
        {
            ExceptionHelper.HandleException(ex, ExceptionPolicyEnum.UI_Policy);
            MessageBox.Show("Error on loading data", MessageType.Error);
        }
    }
    //protected void DepartmentDropDownList_SelectedIndexChanged(object sender, EventArgs e)
    //{
    //    try
    //    {
    //        string SQL_String = string.Empty;

    //        if (DepartmentDropDownList.SelectedIndex > 0)
    //        {

    //            int OrgId = SecuritySession.UserProfile.OrgId;
    //            //int BatchId = SecuritySession.UserProfile.BatchId;
    //            int DepartmentId = int.Parse(DepartmentDropDownList.SelectedValue);
    //            //string AttendanceEntryBasedOn = (ConfigurationHelper.GetUserConfigurationValue("Attendance.AttendanceEntryBasedOn"));
    //            //if (SecuritySession.UserProfile.UserSourceTypeId == 95)
    //            //{
    //            //    if (AttendanceEntryBasedOn == "Class Teacher")
    //            //    {
    //            //        SQL_String = "SELECT DISTINCT Cm.Id AS ClassId, CM.DisplayTitle AS ClassTitle  FROM sSetup.tClassMaster CM INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id WHERE DM.InchargeemployeeID=" + SecuritySession.UserProfile.UserSourceId + "AND CM.DepartmentId=" + DepartmentId + " AND CM.OrgId=" + OrgId;
    //            //        ControllHelperObject.LoadDropDownList(ClassDropDownList, SQL_String, "ClassId", "ClassTitle", false);
    //            //    }
    //            //    else if (AttendanceEntryBasedOn == "Academic Setup")
    //            //    {
    //            //        SQL_String = "SELECT DISTINCT ClassId, ClassTitle,ClassOrderIndex FROM sAcademic.vTeacherSubjectDivision WHERE  EmployeeId=" + SecuritySession.UserProfile.UserSourceId + " AND DepartmentId=" + DepartmentId + " AND OrgId=" + OrgId + " ORDER BY ClassOrderIndex";
    //            //        ControllHelperObject.LoadDropDownList(ClassDropDownList, SQL_String, "ClassId", "ClassTitle", false);
    //            //    }
    //            //    else if (AttendanceEntryBasedOn == "User Access")
    //            //    {
    //            SQL_String = "Select DISTINCT Cm.Id,Cm.Title,CM.OrderIndex from sSetup.tClassMaster CM INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id" +
    //                         " INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id Where DM.OrgId =" + OrgId + "  AND CM.DepartmentId=" + DepartmentId + " AND U.SourceTypeId=2005 AND U.UserId = " + SecuritySession.UserProfile.UserId;
    //            ControllHelperObject.LoadDropDownList(ClassDropDownList, SQL_String, "Id", "Title", false);
    //            //    }
    //            //}
    //            //else
    //            //{
    //            //    SQL_String = string.Empty;
    //            //    SQL_String = "SELECT ClassId, ClassName FROM sSetup.vBatchClass WHERE IsObsolete = 0  AND DepartmentId=" + DepartmentId + " AND BatchId=" + BatchId + " ORDER BY OrderIndex";
    //            //    ControllHelperObject.LoadDropDownList(ClassDropDownList, SQL_String, "ClassId", "ClassName", false);
    //            //}
    //            //SQL_String = "SELECT ClassId, ClassName FROM sSetup.vBatchClass WHERE IsObsolete = 0 AND DepartmentId=" + DepartmentDropDownList.SelectedValue + " AND BatchId=" + SecuritySession.UserProfile.BatchId + " ORDER BY OrderIndex";
    //            //ControllHelperObject.LoadDropDownList(ClassDropDownList, SQL_String, "ClassId", "ClassName", true);
    //            //int DepartmentId = int.Parse(DepartmentDropDownList.SelectedValue.ToString());
    //            //LoadDropDownListValues(ClassDropDownList, "sSetup.vBatchClass", "ClassId", "ClassName", " IsObsolete = 0  AND DepartmentId=" + DepartmentId, 0, SortOrder.SortCustomAscending, "OrderIndex", true);
    //        }
    //        else
    //        {
    //            ListItem li = new ListItem("- ALL -", "0");

    //            int OrgId = SecuritySession.UserProfile.OrgId;
    //            //int BatchId = SecuritySession.UserProfile.BatchId;
    //            //string AttendanceEntryBasedOn = (ConfigurationHelper.GetUserConfigurationValue("Attendance.AttendanceEntryBasedOn"));
    //            //if (SecuritySession.UserProfile.UserSourceTypeId == 95)
    //            //{
    //            //    if (AttendanceEntryBasedOn == "Class Teacher")
    //            //    {
    //            //        SQL_String = "SELECT DISTINCT Cm.Id AS ClassId, CM.DisplayTitle AS ClassTitle  FROM sSetup.tClassMaster CM INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id WHERE DM.InchargeemployeeID=" + SecuritySession.UserProfile.UserSourceId + " AND CM.OrgId=" + OrgId;
    //            //        ControllHelperObject.LoadDropDownList(ClassDropDownList, SQL_String, "ClassId", "ClassTitle", false);
    //            //    }
    //            //    else if (AttendanceEntryBasedOn == "Academic Setup")
    //            //    {
    //            //        SQL_String = "SELECT DISTINCT ClassId, ClassTitle,ClassOrderIndex FROM sAcademic.vTeacherSubjectDivision WHERE EmployeeId=" + SecuritySession.UserProfile.UserSourceId + " AND OrgId=" + OrgId + " ORDER BY ClassOrderIndex";
    //            //        ControllHelperObject.LoadDropDownList(ClassDropDownList, SQL_String, "ClassId", "ClassTitle", false);
    //            //    }
    //            //    else if (AttendanceEntryBasedOn == "User Access")
    //            //    {
    //            SQL_String = "Select DISTINCT Cm.Id,Cm.Title,CM.OrderIndex from sSetup.tClassMaster CM INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id" +
    //                         " INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id Where DM.OrgId =" + OrgId + " AND U.SourceTypeId=2005 AND U.UserId = " + SecuritySession.UserProfile.UserId;
    //            ControllHelperObject.LoadDropDownList(ClassDropDownList, SQL_String, "ClassId", "ClassTitle", false);
    //            //    }
    //            //}
    //            //else
    //            //{
    //            //    SQL_String = string.Empty;
    //            //    SQL_String = "SELECT ClassId, ClassName FROM sSetup.vBatchClass WHERE IsObsolete = 0 AND BatchId=" + BatchId + " ORDER BY OrderIndex";
    //            //    ControllHelperObject.LoadDropDownList(ClassDropDownList, SQL_String, "ClassId", "ClassName", false);
    //            //}

    //            //SQL_String = "SELECT ClassId, ClassName FROM sSetup.vBatchClass WHERE IsObsolete = 0  AND BatchId=" + SecuritySession.UserProfile.BatchId + " ORDER BY OrderIndex";
    //            //ControllHelperObject.LoadDropDownList(ClassDropDownList, SQL_String, "ClassId", "ClassName", true);
    //            //ClassDropDownList.Items.Clear();
    //            //ClassDropDownList.Items.Insert(0, li);
    //            DivisionDropDownList.Items.Clear();
    //            DivisionDropDownList.Items.Insert(0, li);
    //        }
    //        DepartmentDropDownList.Focus();
    //    }
    //    catch (Exception ex)
    //    {
    //        ExceptionHelper.HandleException(ex, ExceptionPolicyEnum.UI_Policy);
    //        MessageBox.Show("Error on loading data", MessageType.Error);
    //    }
    //}

    protected void ClassDropDownList_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ClassDropDownList.SelectedIndex > 0)
        {
            ClassDropDownList.Focus();
            //Old Code
            //string SQL_String = "Select DISTINCT DM.Id,DM.Title,DM.OrderIndex from sSetup.tClassMaster CM INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id INNER JOIN sSetup.tBatchClass BC ON BC.ClassId = CM.Id " +
            //                " INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id Where BC.BatchId = " + SecuritySession.UserProfile.BatchId + " AND CM.Id=" + ClassDropDownList.SelectedValue + " AND DM.OrgId =" + SecuritySession.UserProfile.OrgId + " AND U.SourceTypeId=2005 AND U.UserId = " + SecuritySession.UserProfile.UserId;
            ////string SQL_String = "SELECT Id, Title FROM sSetup.tDivisionMaster WHERE IsObsolete = 0 AND ClassId=" + ClassDropDownList.SelectedValue + "ORDER BY OrderIndex";
            //ControllHelperObject.LoadDropDownList(DivisionDropDownList, SQL_String, "Id", "Title", true);
            ////int ClassId = int.Parse(ClassDropDownList.SelectedValue.ToString());
            ////LoadDropDownListValues(DivisionDropDownList, "sSetup.tDivisionMaster", "Id", "Title", "IsObsolete = 0 AND ClassId=" + ClassId, 0, SortOrder.SortCustomAscending, "OrderIndex", true);
            //Old Code

            //New Code added on 26 feb 2019

            StringBuilder SB_SQL_String_Division = new StringBuilder(10000);
            DataSet dsFillDivision = new DataSet();
            //SB_SQL_String = "";
            // StringBuilder SB_SQL_String = new StringBuilder(10000);
            // SQL_String = string.Empty;

            SB_SQL_String_Division.Append("Select DISTINCT DM.Id,DM.Title,DM.OrderIndex from sSetup.tClassMaster CM INNER JOIN sSetup.tDivisionMaster DM ON DM.ClassId = CM.Id INNER JOIN sSetup.tBatchClass BC ON BC.ClassId = CM.Id INNER JOIN sSecurity.tUserAccess U ON U.SourceId = DM.Id Where DM.IsObsolete=0 AND BC.BatchId=@BatchId AND CM.Id=@ClassId AND DM.OrgId=@OrgId AND U.SourceTypeId=2005 AND U.UserId=@UserId ORDER BY DM.OrderIndex");

            //SB_SQL_String = "SELECT Id, Title FROM sSetup.vDepartment where IsObsolete = 0 AND OrgId=@OrgId AND UserId = @UserId AND   ( Id = @DepartmentId OR @DepartmentId = 0 ) ORDER BY Title";
            //SQL_String = SQL_String + " select Id,Title from sExamination.tSetupGroupMaster where MainTypeId = @rMainTypeId and OrgId = @rOrgId order by OrderIndex";
            //SQLConnectionFunction objC = new SQLConnectionFunction();
            // DataSet dsFillDrp = new DataSet();
            SQLConnectionFunction objC = new SQLConnectionFunction();
            dsFillDivision = objC.QueryDataReader(SB_SQL_String_Division.ToString(),
                objC.GetSqlParam("@BatchId", SqlDbType.Int, 8, SecuritySession.UserProfile.BatchId.ToString()),
                objC.GetSqlParam("@ClassId", SqlDbType.Int, 8, ClassDropDownList.SelectedValue.ToString()),
                objC.GetSqlParam("@OrgId", SqlDbType.Int, 8, SecuritySession.UserProfile.OrgId.ToString()),
                objC.GetSqlParam("@UserId", SqlDbType.BigInt, 16, SecuritySession.UserProfile.UserId.ToString())

                   );
            if (dsFillDivision.Tables[0].Rows.Count > 0)
            {
                DivisionDropDownList.DataSource = dsFillDivision.Tables[0];
                DivisionDropDownList.DataValueField = "Id";
                DivisionDropDownList.DataTextField = "Title";
                DivisionDropDownList.DataBind();
                ListItem li1 = new ListItem();
                li1.Value = "-1";
                li1.Text = "- ALL -";
                DivisionDropDownList.Items.Insert(0, li1);
                DivisionDropDownList.SelectedIndex = 0;
            }
            else
            {
                DivisionDropDownList.Items.Clear();
                DivisionDropDownList.Items.Insert(0, "- ALL -");
            }

        }
        else
        {
            DivisionDropDownList.Items.Clear();
            DivisionDropDownList.Items.Insert(0, "- ALL -");
        }
        ClassDropDownList.Focus();
        //New Code added on 26 feb 2019
    }

    /// <summary>
    /// Common Function To Load Dropdownlists
    /// </summary>
    /// <param name="DropDownControl"></param>
    /// <param name="TableName"></param>
    /// <param name="KeyFieldName"></param>
    /// <param name="FieldName"></param>
    /// <param name="Condition"></param>
    /// <param name="IncludeId"></param>
    /// <param name="SortOrderObj"></param>
    private void LoadDropDownListValues(DropDownList DropDownControl, string TableName, string KeyFieldName, string FieldName, string Condition, int IncludeId, SortOrder SortOrderObj, string customSortField, bool ShowAll)
    {
        CommonFunctions CommonFunctionsObject = new CommonFunctions();
        LoadDropDown LoadDropDownData = new LoadDropDown();

        DropDownControl.Items.Clear();

        LoadDropDownData.DropDownControlName = DropDownControl;
        LoadDropDownData.TableName = TableName;
        LoadDropDownData.KeyFieldName = KeyFieldName;
        LoadDropDownData.FieldName = FieldName;
        LoadDropDownData.Condition = Condition;
        LoadDropDownData.IncludeId = IncludeId;
        LoadDropDownData.SortOrderObject = SortOrderObj;
        LoadDropDownData.DisplayDefaultTextAsAll = ShowAll;
        LoadDropDownData.CustomSortField = customSortField;

        CommonFunctionsObject.LoadDropDownList(LoadDropDownData);
    }

    #endregion

    #region Private Functions

    /// <summary>
    /// Function To Handle Page Load Activities
    /// </summary>
    private void PageLoadActivities()
    {
        // Clear Search Controls
        ClearControls();
        // Hides StudentMasterGridDiv On Load

        LoadSearchPanelDropDownLists();

        //ViewState["IsEditMode"] = null;

        SetTabIndex();
    }

    /// <summary>
    /// Function To Handle Page Post Back Activities
    /// </summary>
    private void PagePostBackActivities()
    {
        //this.ClearButton.Click += new EventHandler(ClearSearchControls_Click);

        // Function To Register Events For Base Buttons
        RegisterBaseButtonEvents();

        // Function To Load Grid Header
        //loadGridHeader(StudentSearchGridView, StudentGridViewTable);
    }

    private void AvailableStudentDataBind()
    {
        //StudentSearchWithPhotoGridView_GridViewPager.Visible = false;
        StudentSearchGridView_GridViewPager.Visible = true;

        if (StudentManagementSession.AllStudentList == null)
        {
            List<Student> StudentList = new List<Student>();
            StudentList = LoadData(new Student());

            if (StudentList != null)
            {
                StudentSearchGridView.DataSource = StudentList;


            }
            else
            {
                //No Reason Available
                MessageBox.Show(GlobalizationManager.MessageResourceManager.GetStringValue("COM_0130"), MessageType.Info);
            }
        }
        else
        {
            if (OrderByDropDownList.SelectedValue == "1")
                StudentSearchGridView.DataSource = StudentManagementSession.AllStudentList;
            else
            {
                if (Convert.ToBoolean((ConfigurationHelper.GetUserConfigurationValue("Student.IsStudentIDAlphaNumeric"))) == true)
                {
                    StudentSearchGridView.DataSource = StudentManagementSession.AllStudentList.OrderBy(X => X.Code).ToList();
                    StudentManagementSession.AllStudentList = StudentManagementSession.AllStudentList.OrderBy(X => X.Code).ToList();
                }
                else
                {
                    StudentSearchGridView.DataSource = StudentManagementSession.AllStudentList.OrderBy(X => X.Number).ToList();
                    StudentManagementSession.AllStudentList = StudentManagementSession.AllStudentList.OrderBy(X => X.Number).ToList();
                }



            }
        }

        StudentSearchGridView.DataBind();
        StudentSearchGridView_GridViewPager.PagingGridView = StudentSearchGridView;

        StudentMasterGridDiv.Visible = true;
        StudentDiv.Visible = true;
        Div5.Visible = true;
        foreach (GridViewRow dr in StudentSearchGridView.Rows)
        {
            Label StatusLabel = (Label)dr.FindControl("StatLabel");
            if (StatusLabel.Text == "Active")
            {
                StatusLabel.CssClass = "label label-success";
                //StatusLabel.BackColor = System.Drawing.Color.Green;
                //StatusLabel.ForeColor = System.Drawing.Color.White;
                //StatusLabel.Width = 40;
            }
            else if (StatusLabel.Text == "InActive")
            {
                StatusLabel.CssClass = "label  label-warning";
                //StatusLabel.BackColor = System.Drawing.Color.Orange;
                //StatusLabel.ForeColor = System.Drawing.Color.White;
                //StatusLabel.Width = 45;
            }
            else
            {
                StatusLabel.CssClass = "label label-danger";
                //StatusLabel.BackColor = System.Drawing.Color.Red;
                //StatusLabel.ForeColor = System.Drawing.Color.White;
                //StatusLabel.Width = 30;
            }

            Label ClassStatusLabel = (Label)dr.FindControl("ClassStatLabel");
            if (ClassStatusLabel.Text == "Active")
            {
                ClassStatusLabel.CssClass = "label label-success";
                //StatusLabel.BackColor = System.Drawing.Color.Green;
                //StatusLabel.ForeColor = System.Drawing.Color.White;
                //StatusLabel.Width = 40;
            }
            else if (ClassStatusLabel.Text == "InActive")
            {
                ClassStatusLabel.CssClass = "label  label-warning";
                //StatusLabel.BackColor = System.Drawing.Color.Orange;
                //StatusLabel.ForeColor = System.Drawing.Color.White;
                //StatusLabel.Width = 45;
            }
            else
            {
                ClassStatusLabel.CssClass = "label label-danger";
                //StatusLabel.BackColor = System.Drawing.Color.Red;
                //StatusLabel.ForeColor = System.Drawing.Color.White;
                //StatusLabel.Width = 30;
            }
        }
        StudentSearchGridView.Columns[4].Visible = SecurityHelper.IsTaskPermissionAllowed(TaskId.StudentManagement.Student360View, PermissionType.Read);
        SetTabIndex();
    }

    /// <summary>
    /// Function To Load Gridview Header
    /// </summary>
    /// <param name="gridViewName"></param>
    /// <param name="FixedTable"></param>
    private void loadGridHeader(GridView gridViewName, Table FixedTable)
    {
        TableRow headerRow = new TableRow();

        for (int x = 0; x < gridViewName.Columns.Count; x++)
        {
            DataControlField col = gridViewName.Columns[x];

            TableCell headerCell = new TableCell();
            headerCell.BorderStyle = BorderStyle.Solid;
            headerCell.BorderWidth = 1;
            headerCell.Font.Bold = true;

            if (col.SortExpression != "")
            {
                LinkButton lnkHeader = new LinkButton();
                lnkHeader.CommandArgument = col.SortExpression;
                lnkHeader.ForeColor = System.Drawing.Color.White;
                lnkHeader.Text = col.HeaderText;
                headerCell.Controls.Add(lnkHeader);
            }
            else
            {
                headerCell.Text = col.HeaderText;
            }

            headerCell.Width = col.ItemStyle.Width;
            headerCell.HorizontalAlign = col.ItemStyle.HorizontalAlign;
            if (((System.Web.UI.WebControls.WebControl)(headerCell)).Width.Value != 0)
            {
                headerRow.Cells.Add(headerCell);
            }
        }
        FixedTable.Rows.Clear();
        FixedTable.Rows.Add(headerRow);
    }


    #region
    bool AllowCreate;
    //bool AllowSearch;

    #endregion

    private void GetPermission()
    {
        // Gets The Permission Level For Various Functionalities In OTEquipmentScheduling Screen For The Logged In User
        //_CreatePermission 
        AllowCreate = SecurityHelper.IsTaskPermissionAllowed(TaskId.StudentManagement.StudentMaster, PermissionType.Create);
        //AllowSearch = SecurityHelper.IsTaskPermissionAllowed(TaskId.StudentManagement.StudentSearch, PermissionType.Search);


        //SearchButton.Enabled = AllowSearch;
        AddnewButton.Enabled = AllowCreate;
        //DeleteButton.Enabled = AllowDelete;
        AddnewButton.Visible = SecurityHelper.IsTaskPermissionAllowed(TaskId.StudentManagement.StudentMaster, PermissionType.Read);
    }


    #endregion

    #region GridView Paging

    protected void StudentSearchGridView_GridViewPager_FirstRecordClick()
    {
        try
        {
            StudentSearchGridView.PageIndex = 0;
            AvailableStudentDataBind();
        }
        catch (Exception ex)
        {
            ExceptionHelper.HandleException(ex, ExceptionPolicyEnum.UI_Policy);
            MessageBox.Show("Error on loading data", MessageType.Error);
        }
    }

    protected void StudentSearchGridView_GridViewPager_LastRecordClick()
    {
        try
        {
            StudentSearchGridView.PageIndex = StudentSearchGridView.PageCount - 1;
            AvailableStudentDataBind();
        }
        catch (Exception ex)
        {
            ExceptionHelper.HandleException(ex, ExceptionPolicyEnum.UI_Policy);
            MessageBox.Show("Error on loading data", MessageType.Error);
        }
    }

    protected void StudentSearchGridView_GridViewPager_PrevRecordClick(PageNumberArgument pgNumber)
    {
        try
        {
            if (StudentSearchGridView.PageIndex != 0)
            {
                StudentSearchGridView.PageIndex = StudentSearchGridView.PageIndex - 1;
                AvailableStudentDataBind();
            }
        }
        catch (Exception ex)
        {
            ExceptionHelper.HandleException(ex, ExceptionPolicyEnum.UI_Policy);
            MessageBox.Show("Error on loading data", MessageType.Error);
        }
    }

    protected void StudentSearchGridView_GridViewPager_NextRecordClick(PageNumberArgument pgNumber)
    {
        try
        {
            StudentSearchGridView.PageIndex = StudentSearchGridView.PageIndex + 1;
            AvailableStudentDataBind();
        }
        catch (Exception ex)
        {
            ExceptionHelper.HandleException(ex, ExceptionPolicyEnum.UI_Policy);
            MessageBox.Show("Error on loading data", MessageType.Error);
        }
    }

    protected void StudentSearchGridView_GridViewPager_TextBoxValueChange(object sender, EventArgs e)
    {
        try
        {
            StudentSearchGridView.PageIndex = int.Parse(((TextBox)sender).Text) - 1;
            AvailableStudentDataBind();
        }
        catch (Exception ex)
        {
            ExceptionHelper.HandleException(ex, ExceptionPolicyEnum.UI_Policy);
            MessageBox.Show("Error on loading data", MessageType.Error);
        }
    }

    protected void StudentSearchGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        //REMAIN UNHANDLED........
    }

    protected void StudentSearchWithPhotoGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        //REMAIN UNHANDLED........
    }

    protected void StudentSearchGridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {   //To obtain RowCount
        try
        {

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton lnkButton = ((LinkButton)e.Row.FindControl("EditLinkButton"));
                lnkButton.CommandArgument = RowCount.ToString();
                //LinkButton lnkProfileButton = ((LinkButton)e.Row.FindControl("ProfileLinkButton"));
                //lnkProfileButton.CommandArgument = RowCount.ToString();
                LinkButton InDetailButton = ((LinkButton)e.Row.FindControl("InDetailLinkButton"));
                InDetailButton.CommandArgument = RowCount.ToString();
                LinkButton StudentAllLinkButton = ((LinkButton)e.Row.FindControl("StudentAllLinkButton"));
                StudentAllLinkButton.CommandArgument = RowCount.ToString();
                LinkButton ProfileLinkButton = ((LinkButton)e.Row.FindControl("ProfileLinkButton"));
                ProfileLinkButton.CommandArgument = RowCount.ToString();
                StudentSearchGridView.Columns[5].HeaderText = Suidlabel;
                StudentSearchGridView.Columns[6].HeaderText = IdLabel;
                RowCount++;


                System.Web.UI.WebControls.Image StudentImage = ((System.Web.UI.WebControls.Image)e.Row.FindControl("StudentPhoto"));
                Int64 Id = Int64.Parse(StudentSearchGridView.DataKeys[e.Row.RowIndex].Values["Id"].ToString());
                Student StudentData = new Student();
                StudentData = StudentManagementSession.AllStudentList.Find(item => item.Id == Id);

                if (ShowWithPhotoCheckBox.Checked == true)
                {
                    StudentSearchGridView.Columns[12].Visible = true;
                    if (StudentData != null && StudentData.StudentPhoto != null)
                    {


                        byte[] ReturnedThumbnail = (byte[])StudentData.StudentPhoto;

                        using (MemoryStream StartMemoryStream = new MemoryStream(),
                                            NewMemoryStream = new MemoryStream())
                        {
                            // write the string to the stream  
                            StartMemoryStream.Write(ReturnedThumbnail, 0, ReturnedThumbnail.Length);

                            // create the start Bitmap from the MemoryStream that contains the image 

                            if (ReturnedThumbnail.Length > 4)
                            {
                                Bitmap startBitmap = new Bitmap(StartMemoryStream);

                                // set thumbnail height and width proportional to the original image.  
                                int newHeight;
                                int newWidth;
                                double HW_ratio;
                                if (startBitmap.Height > startBitmap.Width)
                                {
                                    newHeight = 95;
                                    HW_ratio = (double)((double)95 / (double)startBitmap.Height);
                                    newWidth = (int)(HW_ratio * (double)startBitmap.Width);
                                }
                                else
                                {
                                    newWidth = 95;
                                    HW_ratio = (double)((double)95 / (double)startBitmap.Width);
                                    newHeight = (int)(HW_ratio * (double)startBitmap.Height);
                                }

                                // create a new Bitmap with dimensions for the thumbnail.  
                                Bitmap newBitmap = new Bitmap(newWidth, newHeight);

                                // Copy the image from the START Bitmap into the NEW Bitmap.  
                                // This will create a thumnail size of the same image.  
                                newBitmap = ResizeImage(startBitmap, newWidth, newHeight);

                                // Save this image to the specified stream in the specified format.  
                                newBitmap.Save(NewMemoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);

                                // Fill the byte[] for the thumbnail from the new MemoryStream.  
                                ReturnedThumbnail = NewMemoryStream.ToArray();
                            }
                            StudentImage.ImageUrl = "data:image/jpg;base64," + Convert.ToBase64String((byte[])ReturnedThumbnail);
                        }
                    }
                }
                else
                {
                    StudentSearchGridView.Columns[12].Visible = false;
                }


            }
        }
        catch (Exception ex)
        {
            ExceptionHelper.HandleException(ex, ExceptionPolicyEnum.UI_Policy);
            MessageBox.Show("Error on loading data", MessageType.Error);
        }
    }

    private static Bitmap ResizeImage(Bitmap image, int width, int height)
    {
        Bitmap resizedImage = new Bitmap(width, height);
        using (Graphics gfx = Graphics.FromImage(resizedImage))
        {
            //int OrientationKey = 0x0112;

            //if (image.PropertyIdList.Contains(OrientationKey))
            //{
            //    var orientation = (int)image.GetPropertyItem(OrientationKey).Value[0];

            //    if(orientation == 2)
            //        image.RotateFlip(RotateFlipType.RotateNoneFlipX);
            //    else if(orientation == 3)
            //        image.RotateFlip(RotateFlipType.Rotate180FlipNone);
            //    else if(orientation == 4)
            //        image.RotateFlip(RotateFlipType.Rotate180FlipX);
            //     else if(orientation == 5)
            //        image.RotateFlip(RotateFlipType.Rotate90FlipX);
            //     else if(orientation == 6)
            //        image.RotateFlip(RotateFlipType.Rotate90FlipNone);
            //     else if(orientation == 7)
            //        image.RotateFlip(RotateFlipType.Rotate270FlipX);
            //     else if(orientation == 8)
            //        image.RotateFlip(RotateFlipType.Rotate270FlipNone);

            //}

            gfx.DrawImage(image, new Rectangle(0, 0, width, height),
               new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel);

        }
        return resizedImage;
    }


    #endregion
    protected void AddRowsToGridDropDownList_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            if (AddRowsToGridDropDownList.SelectedIndex == 0)
                StudentSearchGridView.PageSize = 10;
            else if (AddRowsToGridDropDownList.SelectedIndex == 1)
                StudentSearchGridView.PageSize = 20;
            else if (AddRowsToGridDropDownList.SelectedIndex == 2)
                StudentSearchGridView.PageSize = 50;
            else if (AddRowsToGridDropDownList.SelectedIndex == 3)
                StudentSearchGridView.PageSize = 100;
            else
                AddRowsToGridDropDownList.Focus();

            SearchButton_Click(null, null);
        }
        catch (Exception ex)
        {
            ExceptionHelper.HandleException(ex, ExceptionPolicyEnum.UI_Policy);
            MessageBox.Show("Error on loading data", MessageType.Error);
        }
    }
    protected void ViewLinkButton_Click(object sender, EventArgs e)
    {
        try
        {
            Student StudentData = new Student();
            LinkButton ViewLinkButton = (LinkButton)sender;
            GridViewRow row = (GridViewRow)ViewLinkButton.NamingContainer;
            Session["AcademicIdForView"] = null;
            if (row != null)
            {
                int rowIndex = row.RowIndex;
                Int64 AcademicId = Int64.Parse(StudentSearchGridView.DataKeys[rowIndex].Values["AcademicId"].ToString());
                Session["AcademicIdForView"] = AcademicId.ToString();
            }

            //StudentData.StudentId = Id;
            StudentData.BatchId = SecuritySession.UserProfile.BatchId;
            StudentData.OrgId = SecuritySession.UserProfile.OrgId;
            StudentData.UserSourceTypeId = 2003;
            // GetPageDetail();
            // StudentManagementSession.StudentFullProfile = StudentData;
            ScriptManager.RegisterStartupScript(this, GetType(), "Refresh", "window.open('../../Pages/StudentManagement/Student360View.aspx', 'Student View', 'height=600,width=900,toolbar=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,modal=yes');", true);
            //Response.Redirect("~/Pages/StudentManagement/StudentView.aspx?");
        }
        catch (Exception ex)
        {
            ExceptionHelper.HandleException(ex, ExceptionPolicyEnum.UI_Policy);
            MessageBox.Show("Error on loading data", MessageType.Error);
        }
    }
    private void RedirectToMigration()
    {
        try
        {
            RedirectToMigrationInfo objMigrationFunction = new RedirectToMigrationInfo();
            objMigrationFunction.UserId = SecuritySession.UserProfile.UserId;
            objMigrationFunction.DisplayTitle = SecuritySession.UserProfile.DisplayTitle.ToString();
            objMigrationFunction.BatchId = SecuritySession.UserProfile.BatchId;
            objMigrationFunction.UserSourceId = SecuritySession.UserProfile.UserSourceId;
            objMigrationFunction.UserSourceTypeId = SecuritySession.UserProfile.UserSourceTypeId;
            objMigrationFunction.OrgId = SecuritySession.UserProfile.OrgId;
            objMigrationFunction.OrgGroupBatchId = SecuritySession.UserProfile.OrgGroupBatchId;
            objMigrationFunction.AcademicId = SecuritySession.UserProfile.AcademicId;
            objMigrationFunction.OrgGroupId = SecuritySession.UserProfile.OrgGroupId;
            objMigrationFunction.Key = "StudentUrl";
            string Guidstr = Guid.NewGuid().ToString();
            objMigrationFunction.Guidstr = Guidstr;

            int result = VidyalayaMigrationFunction.RedirectToMigration(objMigrationFunction);
            if (result == 1)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "callFunction", "checkPopupBlocked();", true); //add for mantis: 43180
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "RedirectToMigration", "RedirectToMigration('" + objMigrationFunction.Value + "?Guid=" + Guidstr + "&Module=Student');", true);
                return;
            }
        }
        catch (Exception ex)
        {
            ExceptionHelper.HandleException(ex, ExceptionPolicyEnum.UI_Policy);
            MessageBox.Show("Error on loading data", MessageType.Error);
        }
    }  
}