Imports System.Data
Imports System.Data.SqlClient
Imports Ajax

Partial Class After_SalesService
    Inherits System.Web.UI.Page
    Shared g_User As String
    Shared g_Company As String
    Shared g_FinYear As String
    Shared Category(10) As String
    Shared i As Integer
    Shared City_Kid As String
    Shared City_Code As String
    Shared Kid As String
    'Shared assValue As String
    Shared code As String


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Ajax.Utility.RegisterTypeForAjax(GetType(After_SalesService))
        Try
            If Session("SupplierID") Is Nothing And Session("AdminID") = Nothing Then
                Response.Redirect("listproduct.aspx?sess=expire")
                Exit Sub
            End If

            If (Not IsPostBack) Then        'If IsPostBack is false then
                If Session("SupplierID") Is Nothing Then
                    Response.Redirect("listProduct.aspx")
                    Exit Sub
                End If

                txtValidate.Value = "0"
                btnDelete.Attributes.Add("onclick", "return ConfrmMsg();")
                BtnDeleteContact.Attributes.Add("onclick", "return DeleteMsg();")
                btnUpdate.Attributes.Add("onclick", "return UpdateMsg();")
                BtnUpdateContact.Attributes.Add("onclick", "return UpdateMsg();")
                BtnSaveContact.Attributes.Add("onclick", "return SaveConfirm();")

                txtPCountryCode.Attributes.Add("onkeypress", "return numbersonly(event);")
                txtASS_Amount.Attributes.Add("onkeypress", "return numbersonly(event);")
                txtCityCode.Attributes.Add("onkeypress", "return numbersonly(event);")
                txtPhoneno.Attributes.Add("onkeypress", "return numbersonly(event);")
                txtMCountryCode.Attributes.Add("onkeypress", "return numbersonly(event);")
                txtMobileno.Attributes.Add("onkeypress", "return numbersonly(event);")
                txtExtensionno.Attributes.Add("onkeypress", "return numbersonly(event);")
                txtASS_MinResponseTime.Attributes.Add("onkeypress", "return numbersonly(event);")
                FillCombo() ' function for filling combo
                ClearFields()  ' Function for clear textbox and combo
                If Session("AdminID") <> Nothing Or Session("AdminID") = Nothing Then  ' check whether admin is login or not
                    btnUpdate.Visible = False
                    btnDelete.Visible = False
                    BtnUpdateContact.Visible = False
                    BtnDeleteContact.Visible = False
                    ImageButton4.Visible = False
                    EnableControls(False)
                Else
                    btnUpdate.Visible = False
                    btnDelete.Visible = False
                    BtnUpdateContact.Visible = False
                    BtnDeleteContact.Visible = False
                    btnAddMore.Visible = True
                    EnableControls(False)
                    lbl1.Visible = True
                End If
                Call CheckRights(Me, Session("g_User").ToString, "Service Center")
                Fill_Combo("SELECT AfterSalesService.ASS_Kid, AfterSalesService.ASS_ServiceCenter + '  - ' + City_Master.City_Name AS ServiceStation FROM AfterSalesService INNER JOIN City_Master ON AfterSalesService.ASS_LocationId = City_Master.City_Kid WHERE (AfterSalesService.ASS_CompanyId ='" & Session("g_Company").ToString & "') AND (AfterSalesService.ASS_IsDeleted = 0) AND (AfterSalesService.ASS_SupplierId = '" & Session("SupplierID") & "') AND (AfterSalesService.ASS_UserId = '" & Session("g_User") & "')", ddlExisting)
                Fill_Combo("SELECT AfterSalesService.ASS_Kid, AfterSalesService.ASS_ServiceCenter + '  - ' + City_Master.City_Name AS ServiceStation FROM AfterSalesService INNER JOIN City_Master ON AfterSalesService.ASS_LocationId = City_Master.City_Kid WHERE (AfterSalesService.ASS_CompanyId ='" & Session("g_Company").ToString & "') AND (AfterSalesService.ASS_IsDeleted = 0) AND (AfterSalesService.ASS_SupplierId = '" & Session("SupplierID") & "') AND (AfterSalesService.ASS_UserId = '" & Session("g_User") & "')", ddlServiceStation)
                btnAddMore.Visible = True
                BtnSave.Visible = False
                btnCancel.Visible = False
                BtnAddContact.Visible = True
                BtnSaveContact.Visible = False
                tblservicestationcontact.Visible = False
                tblservicestationcontactheader.Visible = False
                EnableContactControls(False)
                ClearControls()
                getGridData(ddlExisting.SelectedValue.ToString)
                'getGridTable()
                ddlExisting.Focus()
                If Request.QueryString("BackId") = Nothing Then
                    If Session("Index") <> Nothing Then
                        btnBack.Visible = True
                    Else
                        Session("ProductID") = Nothing   ' Sessioon productid set nothing
                        btnBack.Visible = False
                    End If
                Else
                    Session("ProductID") = Nothing
                    Session("Index") = Nothing
                    btnBack.Visible = False
                End If
            End If
            lblError.Text = ""
            BtnSave.Attributes.Add("onclick", "return SaveMsg('" & txtValidate.ClientID & "');")
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")
        End Try
    End Sub

    <Ajax.AjaxMethod()> _
    Public Function AddCity(ByVal strCity As String, ByVal strStateID As String, ByVal strCompanyID As String, ByVal strUserID As String, ByVal strFinancialYearID As String) As String
        Dim KID As String
        KID = NewPrimaryKey(Me)

        If IsAlreadyPresent("Select count(*) from City_Master where City_Name='" & strCity.Trim & "' and City_StateId ='" & strStateID.ToString & "'") Then
            Return "false"
        End If

        Dim con As New SqlConnection()
        con.ConnectionString = System.Configuration.ConfigurationManager.AppSettings("ConnectionString")        'Read the connection string from web.config
        Dim cmd As New SqlCommand()
        cmd.CommandType = CommandType.StoredProcedure
        cmd.CommandText = "City_Master_Proc"
        cmd.Connection = con
        cmd.Parameters.Add(New SqlParameter("@City_Kid", SqlDbType.NVarChar, 10)).Value = KID
        cmd.Parameters.Add(New SqlParameter("@City_Code", SqlDbType.NVarChar, 25)).Value = Generate_Code("Select count(*) from City_Master where City_Code='", "CC").ToString()
        cmd.Parameters.Add(New SqlParameter("@City_Name", SqlDbType.NVarChar, 100)).Value = strCity.Trim
        cmd.Parameters.Add(New SqlParameter("@City_StateId", SqlDbType.NVarChar, 10)).Value = strStateID.Trim
        cmd.Parameters.Add(New SqlParameter("@City_CompanyId", SqlDbType.NVarChar, 10)).Value = Trim(strCompanyID)
        cmd.Parameters.Add(New SqlParameter("@City_UserId", SqlDbType.NVarChar, 10)).Value = Trim(strUserID)
        cmd.Parameters.Add(New SqlParameter("@City_FinancialYearId", SqlDbType.NVarChar, 10)).Value = strFinancialYearID.Trim
        cmd.Parameters.Add(New SqlParameter("@FormName", SqlDbType.NVarChar, 50)).Value = "SupplierRegistration1"
        cmd.Parameters.Add(New SqlParameter("@Mode", SqlDbType.VarChar, 10)).Value = "Insert"
        Try
            con.Open()
            cmd.ExecuteNonQuery()
            con.Close()
            Return KID
        Catch ex As Exception
            con.Close()
            Return "false"
        End Try
        Return True

    End Function

    Public Sub FillGrid(ByVal StrQry As String, ByVal gv As GridView)
        ' used to fill grid acounrding to StrQry Parameter
        Try
            Dim Con As New SqlConnection(ConfigurationManager.AppSettings("ConnectionString")) 'Define connection variable for connecting to SQL-Server
            Con.Open()                                             'Open the Connection
            Dim cmd As New SqlCommand(StrQry, Con)                 'Define command variable to execute the query
            Dim dr As SqlDataReader                                'Define DataReader variable for storing the output of the query
            dr = cmd.ExecuteReader                                 'Assign the output of query to DataReader variable
            gv.Columns(1).Visible = True
            gv.Columns(6).Visible = True
            gv.Columns(8).Visible = True
            gv.DataSource = dr                                     'Set the DataReader Variable as DataSource for the Grid
            gv.DataBind()
            gv.Columns(1).Visible = False
            gv.Columns(6).Visible = False
            gv.Columns(8).Visible = False
            If Con.State = ConnectionState.Open Then Con.Close() ' If Connection Exists Then Close
            Con = Nothing                                        ' Set Connnection Object as nothing       
            cmd = Nothing                                        ' Set Command Object as nothing
            dr = Nothing                                         ' Set DataReader Object as nothing
        Catch ex As Exception
            CreateMessageAlert(gv.Page, ex.Message, "StrKeyVal")     'Display the Error Message
        End Try
    End Sub

    Public Sub FillCategoryName(ByVal Catid As String)
        ' used to fill category hirarchy in label
        Dim dt As DataTable
        dt = ReturnDataTable("Select * From Category_Master Where Category_Kid ='" & Catid & "' and Category_Isdeleted = '0' and Category_CompanyId ='" & Session("g_Company").ToString & "'")
        Dim ParentId As String
        ParentId = dt.Rows(0).Item(3).ToString()
        If ParentId = "Root Category" Then

            Dim j As Integer
            Category(i) = dt.Rows(0).Item(2).ToString() & "  >  "
            'Array.Reverse(Category)
            For j = 0 To i
                lbl1.Text += Category(i)
                i = i - 1
            Next
            Exit Sub
        Else
            Category(i) = dt.Rows(0).Item(2).ToString() & "  >  "
            i = i + 1
            'Label1.Text += dt.Rows(0).Item(2).ToString() & "  >  "
            FillCategoryName(dt.Rows(0).Item(3).ToString())
        End If
        dt.Clear()

    End Sub

    Private Sub getExistingData()
        ' used to get eisting records
        Dim dt As DataTable = getTable("Select * from AfterSalesService where ASS_ProductId='" & Session.Item("ProductID").Trim & "' and ASS_IsDeleted='0' and ASS_CompanyID='" & Session("g_Company").ToString.Trim & "' and ASS_UserID='" & Session("g_User").ToString.Trim & "'", "ASS")

        If dt.Rows.Count > 0 Then
            ' if existing 
            ddlExisting.Visible = False
            lbl1.Visible = False

            ddlASSUId.ClearSelection()
            txtASS_Code.Text = dt.Rows(0).Item("ASS_Code").ToString
            txtASS_Amount.Text = dt.Rows(0).Item("ASS_Amount").ToString
            txtASS_MinResponseTime.Text = dt.Rows(0).Item("ASS_MinResponseTime").ToString
            txtASS_Address.Text = dt.Rows(0).Item("ASS_Address").ToString
            ddlASSUId.ClearSelection()
            ddlASSUId.Items.FindByValue(dt.Rows(0).Item("ASS_UnitId").ToString).Selected = True
            getLocation(dt.Rows(0).Item("ASS_LocationId").ToString)
            txtASS_ServiceCenter.Text = dt.Rows(0).Item("ASS_ServiceCenter").ToString()
            ddlAmountUnit.Items.FindByValue(dt.Rows(0).Item("ASS_AmountUnitID").ToString())

            BtnSave.Visible = False

            EnableControls(False)
        Else
            ' if not existing
            ddlExisting.Visible = True
            lbl1.Visible = True
            FillExistingDropDown("SELECT ASS_productid FROM AfterSalesService WHERE ASS_userid = '" & RemoveLiterals(Session("g_User").ToString.Trim) & "' AND ASS_companyid = '" & Session("g_Company").ToString & "' AND ASS_IsDeleted = N'0'", ddlExisting)
            ' fill Existing Drop Down List
            'r8.Visible = False
            Call GenerateCode()
            BtnSave.Visible = True

        End If
        dt.Clear()
    End Sub

    Public Sub FillExistingDropDown(ByVal strQuery As String, ByVal ddl As DropDownList)
        ' Function To Fill Up Existing DropDorn According To StrQry
        Dim dt1 As DataTable = getTable(strQuery, "PR")
        Dim i As Integer
        Dim Kid As String
        Dim KidBool As Boolean = True

        For i = 0 To dt1.Rows.Count - 1
            If KidBool = True Then
                Kid = "'" & dt1.Rows(i).Item(0).ToString & "'"
                KidBool = False
            Else
                Kid &= ","
                Kid &= "'" & dt1.Rows(i).Item(0).ToString & "'"

            End If

        Next

        Fill_Combo("Select Product_Kid,Product_Name from Product_Master where Product_SupplierID='" & Session.Item("SupplierID").ToString.Trim & "'and Product_IsDeleted = '0' and Product_Kid In ( " & Kid & ")", ddl)
        ' Fill Combo with product name from product master

        If ddl.Items.Count > 1 Then
            ddl.Items.Insert(ddl.Items.Count, "Add New")
            lbl1.Visible = True
            EnableControls(False)
        Else
            lbl1.Visible = False
            ddl.Visible = False
            EnableControls(True)
        End If
        dt1.Clear()
    End Sub

    Private Sub EnableControls(ByVal bool As Boolean)
        txtASS_Address.Enabled = bool
        txtASS_Amount.Enabled = bool
        txtASS_MinResponseTime.Enabled = bool
        txtASS_ServiceCenter.Enabled = bool
        ddlASSUId.Enabled = bool
        ddlCity.Enabled = bool
        ddlCountry.Enabled = bool
        ddlState.Enabled = bool
        ddlAmountUnit.Enabled = bool
        rblType.Enabled = bool
        txtRemarks.Enabled = bool
    End Sub

    Private Sub getLocation(ByVal strLocID As String)
        Try
            ' get city name , state name and country name acoording to strLocID
            Dim strLocaId, strCityID, strStateID, strCountry As String
            strLocaId = strLocID
            'strCityID = ReturnValue("select Location_CityId from Location_Master where Location_Kid='" & strLocaId.Trim & "' and Location_IsDeleted='0' and Location_CompanyID='" & g_Company.Trim & "'")
            strStateID = ReturnValue("select City_StateId from City_Master where City_Kid='" & strLocaId.Trim & "'and City_IsDeleted='0' and City_CompanyID='" & Session("g_Company").ToString.Trim & "'")
            strCountry = ReturnValue("select State_CountryId from State_Master where State_Kid='" & strStateID.Trim & "'and State_IsDeleted='0' and State_CompanyID='" & Session("g_Company").ToString.Trim & "'")
            Fill_Combo("select Country_Kid,Country_Name from Country_Master where Country_IsDeleted='0' and Country_CompanyID='" & Session("g_Company").ToString.Trim & "'", ddlCountry)
            Fill_Combo("select State_Kid,State_Name from State_Master where State_CountryId='" & strCountry.Trim & "'and State_IsDeleted='0' and State_CompanyID='" & Session("g_Company").ToString.Trim & "' ", ddlState)
            Fill_Combo("select City_Kid,City_Name from City_Master where City_StateId='" & strStateID.Trim & "'and City_IsDeleted='0' and City_CompanyID='" & Session("g_Company").ToString.Trim & "'", ddlCity)
            'Fill_Combo("select Location_Kid,Location_Name from Location_Master where Location_CityId='" & strCityID.Trim & "'and Location_IsDeleted='0' and Location_CompanyID='" & g_Company.Trim & "'", ddlASS_LocationId)
            ddlCountry.ClearSelection()
            ddlCountry.Items.FindByValue(strCountry.Trim).Selected = True

            ddlState.ClearSelection()
            ddlState.Items.FindByValue(strStateID.Trim).Selected = True

            ddlCity.ClearSelection()
            ddlCity.Items.FindByValue(strLocaId.Trim).Selected = True
        Catch ex As Exception
            Fill_Combo("select Country_Kid,Country_Name from Country_Master where Country_IsDeleted='0' and Country_CompanyID='" & Session("g_Company").ToString.Trim & "'", ddlCountry)
            ddlCountry.ClearSelection()
            ddlCountry.Items.FindByText("India").Selected = True
            Fill_Combo("select State_Kid,State_Name from State_Master where State_CountryId='" & ddlCountry.SelectedItem.Value.Trim & "'and State_IsDeleted='0' and State_CompanyID='" & Session("g_Company").ToString.Trim & "' ", ddlState)
            ddlState.ClearSelection()
            ddlCity.Items.Clear()
        End Try

        'CType(FormView1.FindControl("Label7"), Label).Text = ReturnValue("select Country_Name from Country_Master where Country_Kid='" & strcou.Trim & "'and State_IsDeleted='0' and State_CompanyID='" & g_Company.Trim & "'")


        'ddlASS_LocationId.ClearSelection()
        'ddlASS_LocationId.Items.FindByValue(strLocaId.Trim).Selected = True
    End Sub

    Private Sub FillCombo()

        'fill combo of country, state and unit combo

        'Fill Center Name,Country and Product
        'Fill_Combo("SELECT distinct SS_Kid, SS_CenterName FROM ServiceCenter WHERE SS_IsDeleted = '0' AND SS_CompanyId = '" & g_Company & "' order by SS_CenterName", ddlASS_ServiceCenterId)
        Try
            Fill_Combo("SELECT distinct Country_Kid, Country_Name FROM Country_Master where Country_IsDeleted='0'and Country_CompanyId='" & Session("g_Company").ToString & "' order by Country_Name", ddlCountry)
            ddlCountry.Items.FindByText("India").Selected = True
            Fill_Combo("SELECT State_Master.State_Kid, State_Master.State_Name, Country_Master.Country_Name FROM Country_Master INNER JOIN State_Master ON Country_Master.Country_Kid = State_Master.State_CountryId WHERE State_Master.State_CompanyId = '" & Session("g_Company").ToString & "' AND State_Master.State_IsDeleted = '0' AND Country_Master.Country_Kid = '" & ddlCountry.SelectedItem.Value & "'", ddlState)
            Fill_Combo("Select City_Kid,City_Name from City_Master where City_CompanyId= '" & Session("g_Company").ToString & "' and  City_IsDeleted=0", ddlCity)

        Catch ex As Exception
            ddlCountry.ClearSelection()
            ddlState.Items.Clear()
        End Try
        Try
            FillUnitCombo("select distinct Unit_Kid,Unit_Name from Unit_Master where Unit_IsDeleted='0' and Unit_CompanyId='" & Session("g_Company").ToString.Trim & "'and unit_Flag like 'Days%'", ddlASSUId)
            ddlASSUId.Items.FindByText("Hrs.").Selected = True
        Catch ex As Exception
            ddlAmountUnit.ClearSelection()
        End Try
        Try
            FillUnitCombo("select distinct Unit_Kid,Unit_Name from Unit_Master where Unit_IsDeleted='0' and Unit_CompanyId='" & Session("g_Company").ToString.Trim & "'and unit_Flag like 'Amount%'", ddlAmountUnit)
            ddlAmountUnit.Items.FindByText("Rs.").Selected = True
        Catch ex As Exception
            ddlAmountUnit.ClearSelection()
        End Try
    End Sub

    Public Sub FillUnitCombo(ByVal strQuery As String, ByVal ddl As DropDownList)
        ' fill unit combo
        Try
            Dim SqlCon As New SqlConnection(ConfigurationManager.AppSettings("ConnectionString"))  ' Declare connection Object
            Dim SqlAdapter As New SqlDataAdapter      ' Declare Dataadapter Object
            Dim SqlDataSet As New Data.DataSet        ' Declare Dataset Object
            Dim DT As New Data.DataTable              ' Declare Datatable Oblect
            Dim sqlCmd As New SqlCommand(strQuery, SqlCon) ' Declare Command Object
            Dim i As Integer

            SqlCon.Open()                                 ' Open Connection
            SqlAdapter.SelectCommand = sqlCmd             ' Set command to Adapter
            SqlAdapter.Fill(SqlDataSet, "TableName")      ' Links Adapter with DataSet
            DT = SqlDataSet.Tables("TableName")           ' Get datatable from dataset
            sqlCmd.ExecuteNonQuery()                      ' Executes Command

            ddl.Items.Clear()                             ' Clear the Items of DropDownList  

            For i = 0 To DT.Rows.Count - 1
                ddl.Items.Insert(i, New ListItem(DT.Rows(i).Item(1), DT.Rows(i).Item(0)))  '' Add Items(code,Exact Value) into DropDownList
            Next i
            ' ddl.SelectedIndex = ddl.Items.IndexOf(ddl.Items.FindByValue(""))     '' Assigning 0 th Index to DropDownList

            SqlCon.Close()                                '' Close Connection Object
            SqlCon.Dispose()                              '' Dispose Connection Oblect
            sqlCmd.Dispose()                              '' Dispose command object
            SqlAdapter.Dispose()                          '' Dispose adapter Object
            SqlDataSet.Dispose()                          '' Dispose dataset Object
            DT.Clear()
            DT.Dispose()                                  '' Dispose datatable Object
        Catch ex As Exception
            CreateMessageAlert(ddl.Page, ex.Message, "StrKeyVal")     'Display the Error Message
            ddl = Nothing
        End Try
    End Sub

    Protected Sub _Default_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        If Not IsValidConnectionString() Then CreateMessageAlert(Me, "Check the Connection String !", "StrKeyVal") 'If not a valid ConnectionString then Display the message 
    End Sub

    Protected Sub ClearFields()
        txtASS_Code.Text = ""
        'ddlASS_ServiceCenterId.SelectedIndex = 0
        txtASS_Amount.Text = ""
        txtRemarks.Text = ""
        txtASS_Address.Text = ""
        'txtASS_ServiceBy.Text = ""
        txtASS_ServiceCenter.Text = ""
        txtASS_MinResponseTime.Text = ""
        ddlCountry.ClearSelection()
        ddlCountry.Items.FindByText("India").Selected = True
        Fill_Combo("SELECT State_Master.State_Kid, State_Master.State_Name, Country_Master.Country_Name FROM Country_Master INNER JOIN State_Master ON Country_Master.Country_Kid = State_Master.State_CountryId WHERE State_Master.State_CompanyId = '" & Session("g_Company").ToString & "' AND State_Master.State_IsDeleted = '0' AND Country_Master.Country_Kid = '" & ddlCountry.SelectedValue & "'", ddlState)
        ddlCity.Items.Clear()
        'ddlASS_LocationId.SelectedIndex = -1
        txtASS_Address.Text = ""
    End Sub

    'Protected Sub ddlCountry_Code_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlCountry.SelectedIndexChanged

    '    Try
    '        Fill_Combo("SELECT State_Master.State_Kid, State_Master.State_Name, Country_Master.Country_Name FROM Country_Master INNER JOIN State_Master ON Country_Master.Country_Kid = State_Master.State_CountryId WHERE State_Master.State_CompanyId = '" & Session("g_Company").ToString & "' AND State_Master.State_IsDeleted = '0' AND Country_Master.Country_Kid = '" & ddlCountry.SelectedValue & "'", ddlState)
    '        ddlCity.Items.Clear()
    '        '            ScriptManager.RegisterClientScriptBlock(sender, sender.GetType(), "MyKey", "WebForm_AutoFocus('" + ddlState.ClientID + "');", True)

    '    Catch ex As Exception
    '        CreateMessageAlert(Me, ex.Message, "StrKeyVal")     'Display the Error Message
    '    End Try
    'End Sub

    'Protected Sub ddlState_Code_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlState.SelectedIndexChanged
    '    Try
    '        Fill_Combo("SELECT distinct City_Master.City_Kid, City_Master.City_Name, State_Master.State_Name, City_Master.City_CompanyId FROM City_Master INNER JOIN  State_Master ON City_Master.City_StateId = State_Master.State_Kid WHERE City_Master.City_IsDeleted = '0' AND City_Master.City_CompanyId = '" & Session("g_Company").ToString & "' AND State_Master.State_Kid = '" & ddlState.SelectedValue & "'", ddlCity)
    '        ddlCity.Items.Add("Others")
    '        'ScriptManager.RegisterClientScriptBlock(sender, sender.GetType(), "MyKey", "WebForm_AutoFocus('" + ddlCity_Code.ClientID + "');", True)
    '        ddlCity.Enabled = True
    '        ddlCity.Attributes.Add("onchange", "return checkCityddl(this,'" & ddlState.SelectedItem.Value.ToString & "','" & Session("g_Company").ToString & "','" & Session("g_User") & "','" & Session("g_FinYear") & "');")
    '    Catch ex As Exception
    '        CreateMessageAlert(Me, ex.Message, "StrKeyVal")     'Display the Error Message
    '    End Try
    'End Sub

    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnSave.Click
        Try

            ' If txtValidate.Text = "0" Then
            'DvASSS.Visible = True
            lblError.Visible = False
            GenerateCode()
            hf1.Value = txtASS_ServiceCenter.Text
            hf2.Value = ddlCity.SelectedItem.Text
            Dim con As New SqlConnection
            con.ConnectionString = System.Configuration.ConfigurationManager.AppSettings("ConnectionString")
            Dim cmd As New SqlCommand
            cmd.CommandType = CommandType.StoredProcedure
            cmd.CommandText = " AfterSalesService_Proc"
            cmd.Connection = con
            cmd.Parameters.Add(New SqlParameter("@ASS_Kid", SqlDbType.NVarChar, 20)).Value = NewPrimaryKey(Me)
            cmd.Parameters.Add(New SqlParameter("@ASS_Code", SqlDbType.NVarChar, 20)).Value = Trim(txtASS_Code.Text)
            cmd.Parameters.Add(New SqlParameter("@ASS_ServiceCenterType", SqlDbType.NVarChar, 100)).Value = Trim(rblType.SelectedItem.Text)
            cmd.Parameters.Add(New SqlParameter("@ASS_ServiceCenter", SqlDbType.NVarChar, 100)).Value = Trim(txtASS_ServiceCenter.Text.Trim)
            cmd.Parameters.Add(New SqlParameter("@ASS_Amount", SqlDbType.NVarChar, 25)).Value = Trim(txtASS_Amount.Text)
            cmd.Parameters.Add(New SqlParameter("@ASS_AmountUnitID", SqlDbType.NVarChar, 10)).Value = Trim(ddlAmountUnit.SelectedItem.Value)
            cmd.Parameters.Add(New SqlParameter("@ASS_MinResponseTime", SqlDbType.NVarChar, 25)).Value = Trim(txtASS_MinResponseTime.Text)
            cmd.Parameters.Add(New SqlParameter("@ASS_Remarks", SqlDbType.NVarChar, 250)).Value = Trim(txtRemarks.Text.Trim)
            cmd.Parameters.Add(New SqlParameter("@ASS_UnitId", SqlDbType.NVarChar, 10)).Value = RemoveLiterals(ddlASSUId.SelectedValue.Trim)
            cmd.Parameters.Add(New SqlParameter("@ASS_LocationId", SqlDbType.NVarChar, 20)).Value = RemoveLiterals(ddlCity.SelectedValue.Trim)
            cmd.Parameters.Add(New SqlParameter("@ASS_Address", SqlDbType.NVarChar, 25)).Value = Trim(txtASS_Address.Text)
            cmd.Parameters.Add(New SqlParameter("@ASS_SupplierId", SqlDbType.NVarChar, 10)).Value = Trim(Session("SupplierID"))
            cmd.Parameters.Add(New SqlParameter("@ASS_FinancialYearId", SqlDbType.NVarChar, 20)).Value = Trim(Session("g_FinYear").ToString)
            cmd.Parameters.Add(New SqlParameter("@ASS_CompanyId", SqlDbType.NVarChar, 20)).Value = Trim(Session("g_Company").ToString)
            cmd.Parameters.Add(New SqlParameter("@ASS_UserId", SqlDbType.NVarChar, 20)).Value = Trim(Session("g_User").ToString)
            cmd.Parameters.Add(New SqlParameter("@FormName", SqlDbType.NVarChar, 100)).Value = "After Sales Service"
            cmd.Parameters.Add(New SqlParameter("@Mode", SqlDbType.VarChar, 50)).Value = "Insert"
            If con.State = ConnectionState.Open Then ' check whether connection is opened or not
                con.Close()
            End If
            con.Open()
            cmd.ExecuteNonQuery()
            'hf1.Value = txtASS_ServiceCenter.Text + "  - " + ddlCity.SelectedItem.Text
            CreateMessageAlert(Me, "Service Station Information Saved Successfully.\n" + "\nTo Add Contact Information Click on Add Contact Button.", "StrKeyVal")
            BtnAddContact.Focus()
            ShowMessage("Record Saved Successfully")
            con.Close() ' close connection
            Fill_Combo("SELECT AfterSalesService.ASS_Kid, AfterSalesService.ASS_ServiceCenter + '  - ' + City_Master.City_Name AS ServiceStation FROM AfterSalesService INNER JOIN City_Master ON AfterSalesService.ASS_LocationId = City_Master.City_Kid WHERE (AfterSalesService.ASS_CompanyId ='" & Session("g_Company").ToString & "') AND (AfterSalesService.ASS_IsDeleted = 0) AND (AfterSalesService.ASS_SupplierId = '" & Session("SupplierID") & "') AND (AfterSalesService.ASS_UserId = '" & Session("g_User") & "')", ddlExisting)
            Fill_Combo("SELECT AfterSalesService.ASS_Kid, AfterSalesService.ASS_ServiceCenter + '  - ' + City_Master.City_Name AS ServiceStation FROM AfterSalesService INNER JOIN City_Master ON AfterSalesService.ASS_LocationId = City_Master.City_Kid WHERE (AfterSalesService.ASS_CompanyId ='" & Session("g_Company").ToString & "') AND (AfterSalesService.ASS_IsDeleted = 0) AND (AfterSalesService.ASS_SupplierId = '" & Session("SupplierID") & "') AND (AfterSalesService.ASS_UserId = '" & Session("g_User") & "')", ddlServiceStation)
            con.Dispose()
            FillCombo()

            EnableControls(False)
            ddlExisting.Enabled = True
            SaveClickVisible(Me, btnAddMore, BtnSave, btnUpdate, btnDelete, btnCancel)
            ClearFields()
            ' java script code starts here 

            'Dim sString As System.Text.StringBuilder
            'sString = New System.Text.StringBuilder
            'sString.Append("JJTest();")
            'sString.Append("<script language='Javascript'>")
            ''sString.Append("var res= confirm('This template name already exists!, Overwrite?');")
            ''sString.Append("if (res == 1) {" & vbCrLf)
            ''sString.Append("document.getElementById(" & txtValidate.ClientID.ToString & ").value = 1;" & vbCrLf)
            'sString.Append("JJTest();" & vbCrLf)
            ''sString.Append("}" & vbCrLf)
            'sString.Append("</script>")
            ''Page.ClientScript.RegisterStartupScript(Me.GetType(), "ClientScript", sString.ToString())
            '  ScriptManager.RegisterStartupScript(Me, Me.GetType, "ClientScript", "JJTest();", True)

            ' ElseIf txtValidate.Text = "1" Then

            'tblservicestation.Visible = False

            'tblservicestationheader.Visible = False
            'tblservicestationcontactheader.Visible = True
            'tblservicestationcontact.Visible = True
            ''tblservicestation.Style.Add("display", "none")
            'tblservicestationheader.Style.Add("display", "none")
            'tblservicestationcontactheader.Style.Add("display", "auto")
            'tblservicestationcontact.Style.Add("display", "auto")

            'EnableContactControls(True)
            'ClearControls()
            'Fill_Combo("SELECT AfterSalesService.ASS_Kid, AfterSalesService.ASS_ServiceCenter + '  - ' + City_Master.City_Name AS ServiceStation FROM AfterSalesService INNER JOIN City_Master ON AfterSalesService.ASS_LocationId = City_Master.City_Kid WHERE (AfterSalesService.ASS_CompanyId ='" & Session("g_Company").ToString & "') AND (AfterSalesService.ASS_IsDeleted = 0) AND (AfterSalesService.ASS_SupplierId = '" & Session("SupplierID") & "') AND (AfterSalesService.ASS_UserId = '" & Session("g_User") & "')", ddlServiceStation)
            'ddlServiceStation.Items.FindByText(hf1.Value).Selected = True
            'ddlServiceStation.Enabled = False
            'AddClickVisible(Me, BtnAddContact, BtnSaveContact, BtnUpdateContact, BtnDeleteContact, btnCancelContact)
            ''   txtValidate.Text = "0"
            'Else
            'SaveClickVisible(Me, btnAddMore, BtnSave, btnUpdate, btnDelete, btnCancel)
            'txtValidate.Text = "0"
            'End If
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")                                 'Display the Error Message
        End Try

    End Sub

    Protected Sub GenerateCode()
        Try
            Dim i As String
            Dim qry As String
            Dim code As String
            i = "1"
            i = Format(Val(i), "000")
            While True
                code = "ASS" & "/" & Year(Date.Today) & "/" & Format(Month(Date.Today), "00") & "/" & Day(Date.Today) & "/" & i
                qry = "select count(*) from AfterSalesService where ASS_Code='" & code & "'"
                If IsAlreadyPresent(qry) Then
                    i = Val(i) + 1
                    i = Format(Val(i), "000")
                Else
                    txtASS_Code.Text = code
                    Exit Sub
                End If
            End While
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")     'Display the Error Message
        End Try
    End Sub

    Protected Sub BtnSkip_Click(ByVal sender As Object, ByVal e As System.EventArgs)

    End Sub

    Protected Sub GenerateCityCode()
        Try
            Dim i As String
            Dim qry As String
            Dim code As String
            City_Kid = NewPrimaryKey(Me)
            i = "1"
            i = Format(Val(i), "000")
            While True
                code = "CT" & "/" & Year(Date.Today) & "/" & Format(Month(Date.Today), "00") & "/" & Day(Date.Today) & "/" & i
                qry = "select count(*) from City_Master where City_Code='" & code & "'"
                If IsAlreadyPresent(qry) Then
                    i = Val(i) + 1
                    i = Format(Val(i), "000")
                Else
                    City_Code = code
                    Exit Sub
                End If
            End While
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")     'Display the Error Message
        End Try
    End Sub

    Protected Sub ddlExisting_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlExisting.SelectedIndexChanged
        If ddlExisting.SelectedIndex > 0 Then
            If ddlExisting.SelectedItem.Text = "Add New" Then
                EnableControls(True)
                ClearFields()
                FillCombo()
            Else
                If Session("AdminID") <> Nothing Or Session("AdminID") = Nothing Then
                    EnableControls(True)
                    btnAddMore.Visible = False
                    btnUpdate.Visible = True
                    btnDelete.Visible = True
                    btnCancel.Visible = True
                Else
                    EnableControls(False)
                    btnAddMore.Visible = True
                End If
                Dim Kid As String = ddlExisting.SelectedItem.Value
                Dim dt As DataTable
                dt = ReturnDataTable("SELECT AfterSalesService.ASS_Code,AfterSalesService.ASS_ServiceCenterType, AfterSalesService.ASS_ServiceCenter, AfterSalesService.ASS_Remarks, AfterSalesService.ASS_Amount,AfterSalesService.ASS_AmountUnitID, AfterSalesService.ASS_MinResponseTime, AfterSalesService.ASS_UnitId, AfterSalesService.ASS_LocationId,AfterSalesService.ASS_Address,Country_Master.Country_Kid,State_Master.State_Kid,City_Master.City_Kid FROM Country_Master INNER JOIN State_Master ON Country_Master.Country_Kid = State_Master.State_CountryId INNER JOIN City_Master ON State_Master.State_Kid = City_Master.City_StateId INNER JOIN AfterSalesService ON City_Master.City_Kid = AfterSalesService.ASS_LocationId where AfterSalesService.ASS_Kid='" & Kid & "' and AfterSalesService.ASS_UserId='" & Session("g_User") & "' and AfterSalesService.ASS_CompanyId='" & Session("g_Company") & "' and ASS_SupplierId='" & Session("SupplierID") & "' and AfterSalesService.ASS_IsDeleted=0")
                If dt.Rows.Count = 0 Then
                    ShowMessage("There is no Row in the Data base")
                Else
                    Try
                        If IsDBNull(dt.Rows(0).Item("ASS_ServiceCenterType")) = True Then
                            rblType.ClearSelection()
                        Else
                            rblType.SelectedIndex = rblType.Items.IndexOf(rblType.Items.FindByValue(dt.Rows(0).Item("ASS_ServiceCenterType").ToString().Trim))
                            rblType.Enabled = False
                        End If
                        If IsDBNull(dt.Rows(0).Item("ASS_Code")) = True Then
                            txtASS_Code.Text = ""
                        Else
                            txtASS_Code.Text = dt.Rows(0).Item("ASS_Code").ToString()
                        End If
                        If IsDBNull(dt.Rows(0).Item("ASS_Address")) = True Then
                            txtASS_Address.Text = ""
                        Else
                            txtASS_Address.Text = dt.Rows(0).Item("ASS_Address").ToString()
                        End If
                        If IsDBNull(dt.Rows(0).Item("ASS_Amount")) = True Then
                            txtASS_Amount.Text = ""
                        Else
                            txtASS_Amount.Text = dt.Rows(0).Item("ASS_Amount").ToString()
                        End If
                        If IsDBNull(dt.Rows(0).Item("ASS_MinResponseTime")) = True Then
                            txtASS_MinResponseTime.Text = ""
                        Else
                            txtASS_MinResponseTime.Text = dt.Rows(0).Item("ASS_MinResponseTime").ToString()
                        End If
                        If IsDBNull(dt.Rows(0).Item("ASS_ServiceCenter")) = True Then
                            txtASS_ServiceCenter.Text = ""
                        Else
                            txtASS_ServiceCenter.Text = dt.Rows(0).Item("ASS_ServiceCenter").ToString()
                        End If
                        If IsDBNull(dt.Rows(0).Item("ASS_Remarks")) = True Then
                            txtRemarks.Text = ""
                        Else
                            txtRemarks.Text = dt.Rows(0).Item("ASS_Remarks").ToString()
                        End If
                        FillCombo()

                        ddlAmountUnit.SelectedIndex = ddlAmountUnit.Items.IndexOf(ddlAmountUnit.Items.FindByValue(dt.Rows(0).Item("ASS_AmountUnitID")))
                        ddlASSUId.SelectedIndex = ddlASSUId.Items.IndexOf(ddlASSUId.Items.FindByValue(dt.Rows(0).Item("ASS_UnitId")))
                        ddlCountry.SelectedIndex = ddlCountry.Items.IndexOf(ddlCountry.Items.FindByValue(dt.Rows(0).Item("Country_Kid")))
                        ddlState.SelectedIndex = ddlState.Items.IndexOf(ddlState.Items.FindByValue(dt.Rows(0).Item("State_Kid")))
                        ddlCity.SelectedIndex = ddlCity.Items.IndexOf(ddlCity.Items.FindByValue(dt.Rows(0).Item("ASS_LocationId")))
                    Catch ex As Exception

                    End Try
                    'GridClick(Me, btnAdd, BtnSave, btnUpdate, BtnDelete, btnCancel, btnSearch)
                End If

            End If
            ''BtnSave.Enabled = False
            ''btnAddMore.Enabled = True


            BtnSave.Visible = False
            getGridData(ddlExisting.SelectedValue.ToString)
        Else
            btnUpdate.Visible = False
            btnAddMore.Visible = True
            btnDelete.Visible = False
            btnCancel.Visible = False
            EnableControls(False)
            ClearFields()
            getGridData(ddlExisting.SelectedValue.ToString)
        End If
    End Sub

    Protected Sub btnAddMore_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddMore.Click
        Try
            '            ScriptManager.RegisterClientScriptBlock(sender, sender.GetType(), "MyKey", "WebForm_AutoFocus('" + ddlExisting.ClientID + "');", True)
            EnableControls(True)
            ClearFields()
            tblservicestationcontact.Visible = False
            tblservicestationcontactheader.Visible = False
            tblservicestation.Visible = True
            tblservicestationheader.Visible = True
            ddlASSUId.Visible = True
            ddlAmountUnit.Visible = True
            ddlCountry.Visible = True
            ddlState.Visible = True
            ddlCity.Visible = True
            ddlExisting.Visible = True
            btnAddMore.Visible = False
            BtnSave.Visible = True
            ddlExisting.SelectedIndex = 0
            ddlExisting.Enabled = False
            AddClickVisible(Me, btnAddMore, BtnSave, btnUpdate, btnDelete, btnCancel)
        Catch ex As Exception

        End Try
    End Sub

    Protected Sub btnUpdate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
        Try
            lblError.Visible = False
            GenerateCode()
            Dim con As New SqlConnection
            con.ConnectionString = System.Configuration.ConfigurationManager.AppSettings("ConnectionString")
            Dim cmd As New SqlCommand
            cmd.CommandType = CommandType.StoredProcedure
            cmd.CommandText = " AfterSalesService_Proc"
            cmd.Connection = con
            cmd.Parameters.Add(New SqlParameter("@ASS_Kid", SqlDbType.NVarChar, 20)).Value = RemoveLiterals(ddlExisting.SelectedItem.Value.ToString.Trim)
            cmd.Parameters.Add(New SqlParameter("@ASS_Code", SqlDbType.NVarChar, 20)).Value = RemoveLiterals(ReturnValue("select AfterSalesService.ASS_Code from AfterSalesService where AfterSalesService.ASS_kid='" & RemoveLiterals(ddlExisting.SelectedItem.Value.ToString.Trim) & "'"))
            cmd.Parameters.Add(New SqlParameter("@ASS_ServiceCenterType", SqlDbType.NVarChar, 100)).Value = Trim(rblType.SelectedItem.Text)
            cmd.Parameters.Add(New SqlParameter("@ASS_ServiceCenter", SqlDbType.NVarChar, 25)).Value = Trim(txtASS_ServiceCenter.Text)
            cmd.Parameters.Add(New SqlParameter("@ASS_Amount", SqlDbType.NVarChar, 25)).Value = Trim(txtASS_Amount.Text)
            cmd.Parameters.Add(New SqlParameter("@ASS_AmountUnitID", SqlDbType.NVarChar, 10)).Value = Trim(ddlAmountUnit.SelectedItem.Value)
            'cmd.Parameters.Add(New SqlParameter("@ASS_ServiceBy", SqlDbType.NVarChar, 20)).Value = Trim(txtASS_ServiceBy.Text)
            cmd.Parameters.Add(New SqlParameter("@ASS_MinResponseTime", SqlDbType.NVarChar, 25)).Value = Trim(txtASS_MinResponseTime.Text)
            cmd.Parameters.Add(New SqlParameter("@ASS_Remarks", SqlDbType.NVarChar, 200)).Value = Trim(txtRemarks.Text)
            cmd.Parameters.Add(New SqlParameter("@ASS_UnitId", SqlDbType.NVarChar, 10)).Value = RemoveLiterals(ddlASSUId.SelectedValue.Trim)
            cmd.Parameters.Add(New SqlParameter("@ASS_LocationId", SqlDbType.NVarChar, 20)).Value = RemoveLiterals(ddlCity.SelectedValue.Trim)
            cmd.Parameters.Add(New SqlParameter("@ASS_Address", SqlDbType.NVarChar, 25)).Value = Trim(txtASS_Address.Text)
            cmd.Parameters.Add(New SqlParameter("@ASS_SupplierId", SqlDbType.NVarChar, 10)).Value = Trim(Session("SupplierID"))
            cmd.Parameters.Add(New SqlParameter("@ASS_FinancialYearId", SqlDbType.NVarChar, 20)).Value = Trim(Session("g_FinYear").ToString)
            cmd.Parameters.Add(New SqlParameter("@ASS_CompanyId", SqlDbType.NVarChar, 20)).Value = Trim(Session("g_Company").ToString)
            cmd.Parameters.Add(New SqlParameter("@ASS_UserId", SqlDbType.NVarChar, 20)).Value = Trim(Session("g_User").ToString)

            cmd.Parameters.Add(New SqlParameter("@FormName", SqlDbType.NVarChar, 100)).Value = "After Sales Service"
            cmd.Parameters.Add(New SqlParameter("@Mode", SqlDbType.VarChar, 50)).Value = "Update"
            If con.State = ConnectionState.Open Then ' check whether connection is opened or not
                con.Close()
            End If
            con.Open()
            cmd.ExecuteNonQuery()
            CreateMessageAlert(Me, "Service Station Information Updated Successfully.", "StrKeyVal")
            ShowMessage("Record Was Successfully Updated.")
            con.Close() ' close connection
            con.Dispose()
            ClearFields()
            Fill_Combo("SELECT AfterSalesService.ASS_Kid, AfterSalesService.ASS_ServiceCenter + '  - ' + City_Master.City_Name AS ServiceStation FROM AfterSalesService INNER JOIN City_Master ON AfterSalesService.ASS_LocationId = City_Master.City_Kid WHERE (AfterSalesService.ASS_CompanyId ='" & Session("g_Company").ToString & "') AND (AfterSalesService.ASS_IsDeleted = 0) AND (AfterSalesService.ASS_SupplierId = '" & Session("SupplierID") & "') AND (AfterSalesService.ASS_UserId = '" & Session("g_User") & "')", ddlExisting)

            'EditClick(Me, btnAdd, BtnSave, btnUpdate, BtnDelete, btnCancel, btnSearch)
            'DVASS.Visible = True
            'FillGrid("SELECT AfterSalesService.ASS_Kid, AfterSalesService.ASS_Code,AfterSalesService.ASS_Remarks, AfterSalesService.ASS_ServiceCenterType, AfterSalesService.ASS_ServiceCenter, AfterSalesService.ASS_ServiceBy, AfterSalesService.ASS_Amount, AfterSalesService.ASS_AmountUnitID, AfterSalesService.ASS_MinResponseTime, AfterSalesService.ASS_UnitId, AfterSalesService.ASS_LocationId, AfterSalesService.ASS_Address, AfterSalesService.ASS_FinancialYearId, AfterSalesService.ASS_CompanyId, AfterSalesService.ASS_UserId, AfterSalesService.ASS_IsDeleted, City_Master.City_Name, Country_Master.Country_Name, State_Master.State_Name, Product_Master.Product_Name FROM State_Master INNER JOIN City_Master ON State_Master.State_Kid = City_Master.City_StateId INNER JOIN Country_Master ON State_Master.State_CountryId = Country_Master.Country_Kid INNER JOIN AfterSalesService ON City_Master.City_Kid = AfterSalesService.ASS_LocationId INNER JOIN Product_Master ON AfterSalesService.ASS_ProductId = Product_Master.Product_Kid WHERE (AfterSalesService.ASS_ProductId = '" & Session("ProductID") & "')", gvASSS)
            'GetDataTablee() ' get unit name from unit master from unit kid

            EditClickVisible(Me, btnAddMore, BtnSave, btnUpdate, btnDelete, btnCancel)
            ClearFields()
            EnableControls(False)
            getGridData(ddlExisting.SelectedValue.ToString)
        Catch ex As Exception

        End Try
    End Sub

    Protected Sub BtnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        Try
            lblError.Visible = False
            GenerateCode()
            Dim con As New SqlConnection
            con.ConnectionString = System.Configuration.ConfigurationManager.AppSettings("ConnectionString")
            Dim cmd As New SqlCommand
            cmd.CommandType = CommandType.StoredProcedure
            cmd.CommandText = " AfterSalesService_Proc"
            cmd.Connection = con
            cmd.Parameters.Add(New SqlParameter("@ASS_Kid", SqlDbType.NVarChar, 20)).Value = RemoveLiterals(ddlExisting.SelectedItem.Value.ToString.Trim)
            cmd.Parameters.Add(New SqlParameter("@ASS_Code", SqlDbType.NVarChar, 20)).Value = RemoveLiterals(ReturnValue("select AfterSalesService.ASS_Code from AfterSalesService where AfterSalesService.ASS_kid='" & RemoveLiterals(ddlExisting.SelectedItem.Value.ToString.Trim) & "'"))
            cmd.Parameters.Add(New SqlParameter("@ASS_ServiceCenterType", SqlDbType.NVarChar, 100)).Value = Trim(rblType.SelectedItem.Text)
            cmd.Parameters.Add(New SqlParameter("@ASS_ServiceCenter", SqlDbType.NVarChar, 25)).Value = Trim(txtASS_ServiceCenter.Text)
            cmd.Parameters.Add(New SqlParameter("@ASS_Amount", SqlDbType.NVarChar, 25)).Value = Trim(txtASS_Amount.Text)
            cmd.Parameters.Add(New SqlParameter("@ASS_AmountUnitID", SqlDbType.NVarChar, 10)).Value = Trim(ddlAmountUnit.SelectedItem.Value)
            'cmd.Parameters.Add(New SqlParameter("@ASS_ServiceBy", SqlDbType.NVarChar, 20)).Value = Trim(txtASS_ServiceBy.Text)
            cmd.Parameters.Add(New SqlParameter("@ASS_MinResponseTime", SqlDbType.NVarChar, 25)).Value = Trim(txtASS_MinResponseTime.Text)
            cmd.Parameters.Add(New SqlParameter("@ASS_Remarks", SqlDbType.NVarChar, 200)).Value = Trim(txtRemarks.Text)
            cmd.Parameters.Add(New SqlParameter("@ASS_UnitId", SqlDbType.NVarChar, 10)).Value = RemoveLiterals(ddlASSUId.SelectedValue.Trim)
            cmd.Parameters.Add(New SqlParameter("@ASS_LocationId", SqlDbType.NVarChar, 20)).Value = RemoveLiterals(ddlCity.SelectedValue.Trim)
            cmd.Parameters.Add(New SqlParameter("@ASS_Address", SqlDbType.NVarChar, 25)).Value = Trim(txtASS_Address.Text)
            cmd.Parameters.Add(New SqlParameter("@ASS_SupplierId", SqlDbType.NVarChar, 10)).Value = Trim(Session("SupplierID"))
            cmd.Parameters.Add(New SqlParameter("@ASS_FinancialYearId", SqlDbType.NVarChar, 20)).Value = Trim(Session("g_FinYear").ToString)
            cmd.Parameters.Add(New SqlParameter("@ASS_CompanyId", SqlDbType.NVarChar, 20)).Value = Trim(Session("g_Company").ToString)
            cmd.Parameters.Add(New SqlParameter("@ASS_UserId", SqlDbType.NVarChar, 20)).Value = Trim(Session("g_User").ToString)

            cmd.Parameters.Add(New SqlParameter("@FormName", SqlDbType.NVarChar, 100)).Value = "After Sales Service"
            cmd.Parameters.Add(New SqlParameter("@Mode", SqlDbType.VarChar, 50)).Value = "Delete"
            If con.State = ConnectionState.Open Then ' check whether connection is opened or not
                con.Close()
            End If
            con.Open()
            cmd.ExecuteNonQuery()
            ExecuteQuery("Update AfterSalesServiceContacts set ServiceStationContacts_IsDeleted='1' where ServiceStationContacts_AfterSalesServiceId='" & RemoveLiterals(ddlExisting.SelectedItem.Value.ToString.Trim) & "' ")
            CreateMessageAlert(Me, "Service Station Information Deleted SuccessFully.", "StrKeyVal")
            ShowMessage("Record Deleted SuccessFully.")
            con.Close() ' close connection
            con.Dispose()
            ClearFields()
            Fill_Combo("SELECT AfterSalesService.ASS_Kid, AfterSalesService.ASS_ServiceCenter + '  - ' + City_Master.City_Name AS ServiceStation FROM AfterSalesService INNER JOIN City_Master ON AfterSalesService.ASS_LocationId = City_Master.City_Kid WHERE (AfterSalesService.ASS_CompanyId ='" & Session("g_Company").ToString & "') AND (AfterSalesService.ASS_IsDeleted = 0) AND (AfterSalesService.ASS_SupplierId = '" & Session("SupplierID") & "') AND (AfterSalesService.ASS_UserId = '" & Session("g_User") & "')", ddlExisting)

            'DeleteClick(Me, btnAdd, BtnSave, btnUpdate, BtnDelete, btnCancel, btnSearch)
            DeleteClickVisible(Me, btnAddMore, BtnSave, btnUpdate, btnDelete, btnCancel)
            getGridData(ddlExisting.SelectedValue.ToString)

            'DVASS.Visible = True
            'FillGrid("SELECT AfterSalesService.ASS_Kid, AfterSalesService.ASS_Code,AfterSalesService.ASS_Remarks, AfterSalesService.ASS_ServiceCenterType, AfterSalesService.ASS_ServiceCenter, AfterSalesService.ASS_ServiceBy, AfterSalesService.ASS_Amount, AfterSalesService.ASS_AmountUnitID, AfterSalesService.ASS_MinResponseTime, AfterSalesService.ASS_UnitId, AfterSalesService.ASS_LocationId, AfterSalesService.ASS_Address, AfterSalesService.ASS_FinancialYearId, AfterSalesService.ASS_CompanyId, AfterSalesService.ASS_UserId, AfterSalesService.ASS_IsDeleted, City_Master.City_Name, Country_Master.Country_Name, State_Master.State_Name, Product_Master.Product_Name FROM State_Master INNER JOIN City_Master ON State_Master.State_Kid = City_Master.City_StateId INNER JOIN Country_Master ON State_Master.State_CountryId = Country_Master.Country_Kid INNER JOIN AfterSalesService ON City_Master.City_Kid = AfterSalesService.ASS_LocationId INNER JOIN Product_Master ON AfterSalesService.ASS_ProductId = Product_Master.Product_Kid WHERE (AfterSalesService.ASS_ProductId = '" & Session("ProductID") & "')", gvASSS)
            'GetDataTablee() ' get unit name from unit master from unit kid
            ClearFields()
        Catch ex As Exception

        End Try
    End Sub

    Protected Sub BtnAddContact_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnAddContact.Click
        Try

            EnableContactControls(True)
            '            ScriptManager.RegisterClientScriptBlock(sender, sender.GetType(), "MyKey", "WebForm_AutoFocus('" + ddlServiceStation.ClientID + "');", True)
            ClearControls()
            'Fill_Combo("SELECT AfterSalesService.ASS_Kid, AfterSalesService.ASS_ServiceCenter + '  - ' + City_Master.City_Name AS ServiceStation FROM AfterSalesService INNER JOIN City_Master ON AfterSalesService.ASS_LocationId = City_Master.City_Kid WHERE (AfterSalesService.ASS_CompanyId ='" & Session("g_Company").ToString & "') AND (AfterSalesService.ASS_IsDeleted = 0) AND (AfterSalesService.ASS_SupplierId = '" & Session("SupplierID") & "') AND (AfterSalesService.ASS_UserId = '" & Session("g_User") & "')", ddlServiceStation)
            ''BtnSaveContact.Enabled = True
            ''BtnAddContact.Enabled = False
            BtnSaveContact.Visible = True
            BtnAddContact.Visible = False
            AddClickVisible(Me, BtnAddContact, BtnSaveContact, BtnUpdateContact, BtnDeleteContact, btnCancelContact)
            ddlServiceStation.Enabled = True
            EnableControls(False)
            If ddlServiceStation.SelectedIndex > 0 Then
                ddlServiceStation.Enabled = False
                txtContactPerson.Focus()
            Else
                ddlServiceStation.Focus()
                ddlServiceStation.Enabled = True
            End If
        Catch ex As Exception

        End Try
    End Sub
    '===========================================

    '============================================
    Public Sub getGridTable()
        Try
        Catch ex As Exception
        End Try
        'Fill_Grid("SELECT     AfterSalesServiceContacts.ServiceStationContacts_Kid, AfterSalesServiceContacts.ServiceStationContacts_ContactPerson,AfterSalesServiceContacts.ServiceStationContacts_PersonDesignation,AfterSalesService.ASS_ServiceCenter + '- ' + City_Master.City_Name AS ASS_ServiceCenter FROM AfterSalesService INNER JOIN AfterSalesServiceContacts ON AfterSalesService.ASS_Kid = AfterSalesServiceContacts.ServiceStationContacts_AfterSalesServiceId INNER JOIN City_Master ON AfterSalesService.ASS_LocationId = City_Master.City_Kid WHERE     AfterSalesService.ASS_SupplierId = '" & Session("SupplierID") & "' AND ServiceStationContacts_companyid = '" & Session("g_Company") & "' AND ServiceStationContacts_IsDeleted = N'0'", gvsscontact)
        'getTableData()
    End Sub

    Private Sub getGridData(ByVal str As String)
        Try
            Dim dt As New DataTable
            If str.ToString = "Select" Then
                dt = ReturnDataTable("SELECT    AfterSalesServiceContacts.ServiceStationContacts_Kid, AfterSalesServiceContacts.ServiceStationContacts_ContactPerson,AfterSalesServiceContacts.ServiceStationContacts_CCMobile +'-'+ AfterSalesServiceContacts.ServiceStationContacts_MobileNo as ServiceStationContacts_MobileNo ,AfterSalesServiceContacts.ServiceStationContacts_EmailId ,AfterSalesServiceContacts.ServiceStationContacts_PersonDesignation,AfterSalesService.ASS_ServiceCenter + '- ' + City_Master.City_Name AS ASS_ServiceCenter FROM AfterSalesService INNER JOIN AfterSalesServiceContacts ON AfterSalesService.ASS_Kid = AfterSalesServiceContacts.ServiceStationContacts_AfterSalesServiceId INNER JOIN City_Master ON AfterSalesService.ASS_LocationId = City_Master.City_Kid WHERE     AfterSalesService.ASS_SupplierId = '" & Session("SupplierID") & "' AND ServiceStationContacts_companyid = '" & Session("g_Company") & "' AND ServiceStationContacts_IsDeleted = N'0'")

                If dt.Rows.Count < 1 Then
                    tblcontact.Visible = False
                    Table3.Visible = False
                    gvsscontact.Visible = False
                Else
                    tblcontact.Visible = True
                    Table3.Visible = True
                    gvsscontact.Visible = True
                End If
            Else
                dt = ReturnDataTable("SELECT     AfterSalesServiceContacts.ServiceStationContacts_Kid, AfterSalesServiceContacts.ServiceStationContacts_ContactPerson,AfterSalesServiceContacts.ServiceStationContacts_CCMobile +'-'+ AfterSalesServiceContacts.ServiceStationContacts_MobileNo as ServiceStationContacts_MobileNo ,AfterSalesServiceContacts.ServiceStationContacts_EmailId ,AfterSalesServiceContacts.ServiceStationContacts_PersonDesignation,AfterSalesService.ASS_ServiceCenter + '- ' + City_Master.City_Name AS ASS_ServiceCenter FROM AfterSalesService INNER JOIN AfterSalesServiceContacts ON AfterSalesService.ASS_Kid = AfterSalesServiceContacts.ServiceStationContacts_AfterSalesServiceId INNER JOIN City_Master ON AfterSalesService.ASS_LocationId = City_Master.City_Kid WHERE     AfterSalesService.ASS_SupplierId = '" & Session("SupplierID") & "' AND ServiceStationContacts_companyid = '" & Session("g_Company") & "' AND ServiceStationContacts_IsDeleted = N'0' AND AfterSalesService.ASS_Kid = '" & str & "'")
                tblcontact.Visible = True
                Table3.Visible = True
                gvsscontact.Visible = True
            End If
            gvsscontact.DataSource = dt
            gvsscontact.DataBind()
            gvsscontact.SelectedIndex = -1
            gvsscontact.PageIndex = 0

        Catch ex As Exception
        End Try
        'Fill_Grid("SELECT     AfterSalesServiceContacts.ServiceStationContacts_Kid, AfterSalesServiceContacts.ServiceStationContacts_ContactPerson,AfterSalesServiceContacts.ServiceStationContacts_PersonDesignation,AfterSalesService.ASS_ServiceCenter + '- ' + City_Master.City_Name AS ASS_ServiceCenter FROM AfterSalesService INNER JOIN AfterSalesServiceContacts ON AfterSalesService.ASS_Kid = AfterSalesServiceContacts.ServiceStationContacts_AfterSalesServiceId INNER JOIN City_Master ON AfterSalesService.ASS_LocationId = City_Master.City_Kid WHERE     AfterSalesService.ASS_SupplierId = '" & Session("SupplierID") & "' AND ServiceStationContacts_companyid = '" & Session("g_Company") & "' AND ServiceStationContacts_IsDeleted = N'0' AND AfterSalesService.ASS_Kid = '" & ddl.SelectedValue & "'", gvsscontact)
    End Sub

    Public Sub getTableData()
        'Try
        '    Dim dt As DataTable = ReturnDataTable("SELECT  Client_Master.ctm_kid, Client_Master.ctm_name, City_Master.City_Name, Client_Master.ctm_abusiness, client_master.ctm_rcontact1, client_master.ctm_rcontact2 , client_master.ctm_emailid, client_master.ctm_ctp, client_master.ctm_ctpDoc FROM Client_Master INNER JOIN City_Master ON Client_Master.ctm_city = City_Master.City_Kid WHERE ctm_SupplierId = '" & Session("SupplierID") & "' AND ctm_companyid = '" & Session("g_Company") & "' AND ctm_IsDeleted = N'0'")
        '    If dt.Rows.Count > 0 Then
        '        Dim i As Integer
        '        If Session("AdminID") <> Nothing or Session("AdminID") = Nothing Then
        '            gvClienteleDetail.Columns(0).Visible = True
        '        Else
        '            gvClienteleDetail.Columns(0).Visible = False
        '        End If
        '        For i = 0 To gvClienteleDetail.Rows.Count - 1
        '            Dim lblreference As Label = CType(gvClienteleDetail.Rows(i).Cells(4).FindControl("lblgrvRefernece"), Label)
        '            'If dt.Rows(i).Item("ctm_rcontact1").ToString = "0" Then
        '            lblreference.Text = dt.Rows(i).Item("ctm_rcontact1").ToString
        '            'ElseIf dt.Rows(i).Item("ctm_rcontact1").ToString = "1" Then
        '            ' lblreference.Text = "Ms."
        '            'End If
        '            lblreference.Text &= " " & dt.Rows(i).Item("ctm_rcontact2")
        '            ' Dim lblcity As Label = CType(gvClienteleDetail.Rows(i).Cells(7).FindControl("lnkDoc"), Label)
        '            Dim lblDoc As HyperLink = CType(gvClienteleDetail.Rows(i).Cells(7).FindControl("lnkDoc"), HyperLink)
        '            lblDoc.Text = dt.Rows(i).Item("ctm_ctpDoc").ToString
        '            lblDoc.NavigateUrl = "~\Upload Image\Product Image\UploadImages\" & dt.Rows(i).Item("ctm_ctpDoc").ToString

        '            Dim lblCity As Label = CType(gvClienteleDetail.Rows(i).Cells(2).FindControl("lblgvCity"), Label)
        '            lblCity.Text = dt.Rows(i).Item("City_Name").ToString


        '            Dim lblYes As Label = CType(gvClienteleDetail.Rows(i).Cells(7).FindControl("lblYesNo"), Label)
        '            If dt.Rows(i).Item("ctm_ctp").ToString = "Y" Then
        '                lblYes.Text = "Yes"
        '            Else
        '                lblYes.Text = "No"
        '            End If

        '        Next

        '    Else

        '        ' btnSave.Visible = True
        '        ' btnAddMore.Visible = True
        '    End If

        '    If Session("AdminID") <> Nothing or Session("AdminID") = Nothing Then
        '        ' FileUpload1.Visible = True
        '        If dt.Rows.Count > 0 Then
        '            ' unLockControl(True)
        '            btnUpdate.Visible = True
        '            btnSave.Visible = False
        '            ' btnAddMore.Visible = False
        '        Else
        '            ' unLockControl(True)
        '            btnUpdate.Visible = False
        '            btnSave.Visible = True
        '            '    btnAddMore.Visible = True
        '        End If
        '    Else
        '        btnUpdate.Visible = False
        '        btnDelete.Visible = False
        '    End If
        '    dt.Clear()
        'Catch
        'End Try

    End Sub

    Protected Sub BtnSaveContact_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnSaveContact.Click
        Try
            If ddlServiceStation.SelectedIndex = 0 Then
                lblsserror.Text = "Please Select Service Station for Adding Contact."
                Exit Sub
            Else
                'DvASSS.Visible = True
                lblError.Visible = False
                ContactGenerateCode()
                Dim con As New SqlConnection
                con.ConnectionString = System.Configuration.ConfigurationManager.AppSettings("ConnectionString")
                Dim cmd As New SqlCommand
                cmd.CommandType = CommandType.StoredProcedure
                cmd.CommandText = "AfterSalesServiceContacts_Proc"
                cmd.Connection = con
                cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_Kid", SqlDbType.NVarChar, 20)).Value = NewPrimaryKey(Me)
                cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_Code", SqlDbType.NVarChar, 20)).Value = Trim(txtcontactcode.Text)
                cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_ContactPerson", SqlDbType.NVarChar, 100)).Value = Trim(txtContactPerson.Text.Trim)
                cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_PersonDesignation", SqlDbType.NVarChar, 100)).Value = Trim(txtDesignation.Text.Trim)
                cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_CCPhone", SqlDbType.NVarChar, 15)).Value = Trim(txtPCountryCode.Text)
                cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_CtyCPhone", SqlDbType.NVarChar, 15)).Value = Trim(txtCityCode.Text)
                cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_PhoneNo", SqlDbType.NVarChar, 15)).Value = Trim(txtPhoneno.Text)
                cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_PhoneExtn", SqlDbType.NVarChar, 15)).Value = Trim(txtExtensionno.Text)
                cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_CCMobile", SqlDbType.NVarChar, 15)).Value = txtMCountryCode.Text.Trim
                cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_MobileNo", SqlDbType.NVarChar, 15)).Value = Trim(txtMobileno.Text)
                cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_EmailId", SqlDbType.NVarChar, 150)).Value = Trim(txtEmailID.Text)
                cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_AfterSalesServiceId", SqlDbType.NVarChar, 10)).Value = RemoveLiterals(ddlServiceStation.SelectedItem.Value.Trim)
                cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_FinancialYearId ", SqlDbType.NVarChar, 20)).Value = Trim(Session("g_FinYear").ToString)
                cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_CompanyId", SqlDbType.NVarChar, 20)).Value = Trim(Session("g_Company").ToString)
                cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_UserId", SqlDbType.NVarChar, 20)).Value = Trim(Session("g_User").ToString)
                cmd.Parameters.Add(New SqlParameter("@FormName", SqlDbType.NVarChar, 100)).Value = "After Sales Service"
                cmd.Parameters.Add(New SqlParameter("@Mode", SqlDbType.VarChar, 50)).Value = "Insert"
                If con.State = ConnectionState.Open Then ' check whether connection is opened or not
                    con.Close()
                End If
                con.Open()
                cmd.ExecuteNonQuery()
                CreateMessageAlert(Me, "Service Station Contact Saved Successfully.", "StrKeyVal")
                ShowMessage("Service Station Contact Saved Successfully")
                con.Close() ' close connection
                Fill_Combo("SELECT AfterSalesService.ASS_Kid, AfterSalesService.ASS_ServiceCenter + '  - ' + City_Master.City_Name AS ServiceStation FROM AfterSalesService INNER JOIN City_Master ON AfterSalesService.ASS_LocationId = City_Master.City_Kid WHERE (AfterSalesService.ASS_CompanyId ='" & Session("g_Company").ToString & "') AND (AfterSalesService.ASS_IsDeleted = 0) AND (AfterSalesService.ASS_SupplierId = '" & Session("SupplierID") & "') AND (AfterSalesService.ASS_UserId = '" & Session("g_User") & "')", ddlExisting)
                con.Dispose()
                ClearFields()
                FillCombo()
                ''btnAddMore.Enabled = True
                ''BtnSave.Enabled = False
                btnAddMore.Visible = True
                BtnSave.Visible = False
                ClearControls()
                EnableContactControls(False)
                ddlServiceStation.Enabled = True
                'tblservicestationcontact.Visible = False
                'tblservicestationcontactheader.Visible = False
                'tblservicestation .Visible = True
                'tblservicestationheader.Visible = True
                'ddlASSUId.Visible = True
                'ddlAmountUnit.Visible = True
                'ddlCountry.Visible = True
                'ddlState.Visible = True
                'ddlCity.Visible = True
                'ddlExisting.Visible = True

                SaveClickVisible(Me, BtnAddContact, BtnSaveContact, BtnUpdateContact, BtnDeleteContact, btnCancelContact)
                getGridData(ddlServiceStation.SelectedValue.ToString)

            End If
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")                                 'Display the Error Message
        End Try
    End Sub

    Protected Sub ContactGenerateCode()
        Try
            Dim i As String
            Dim qry As String
            Dim code As String
            i = "1"
            i = Format(Val(i), "000")
            While True
                code = "ASS" & "/" & Year(Date.Today) & "/" & Format(Month(Date.Today), "00") & "/" & Day(Date.Today) & "/" & i
                qry = "select count(*) from AfterSalesService where ASS_Code='" & code & "'"
                If IsAlreadyPresent(qry) Then
                    i = Val(i) + 1
                    i = Format(Val(i), "000")
                Else
                    txtcontactcode.Text = code
                    Exit Sub
                End If
            End While
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")     'Display the Error Message
        End Try
    End Sub

    Protected Sub BtnUpdateContact_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnUpdateContact.Click
        Try
            Dim dt As DataTable = ReturnDataTable("SELECT  AfterSalesServiceContacts.* FROM AfterSalesServiceContacts  WHERE ServiceStationContacts_Kid='" & RemoveLiterals(gvsscontact.SelectedDataKey.Value.ToString) & "' and ServiceStationContacts_IsDeleted='0'")
            If dt.Rows.Count > 0 Then
                If ddlServiceStation.SelectedIndex = 0 Then
                    lblsserror.Text = "Please Select Service Station for Adding Contact."
                    Exit Sub
                Else
                    'DvASSS.Visible = True
                    lblError.Visible = False
                    ContactGenerateCode()
                    Dim con As New SqlConnection
                    con.ConnectionString = System.Configuration.ConfigurationManager.AppSettings("ConnectionString")
                    Dim cmd As New SqlCommand
                    cmd.CommandType = CommandType.StoredProcedure
                    cmd.CommandText = "AfterSalesServiceContacts_Proc"
                    cmd.Connection = con
                    cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_Kid", SqlDbType.NVarChar, 20)).Value = RemoveLiterals(dt.Rows(0).Item("ServiceStationContacts_Kid").ToString.Trim)
                    cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_Code", SqlDbType.NVarChar, 20)).Value = RemoveLiterals(dt.Rows(0).Item("ServiceStationContacts_code").ToString.Trim)
                    cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_ContactPerson", SqlDbType.NVarChar, 100)).Value = Trim(txtContactPerson.Text.Trim)
                    cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_PersonDesignation", SqlDbType.NVarChar, 100)).Value = Trim(txtDesignation.Text.Trim)
                    cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_CCPhone", SqlDbType.NVarChar, 15)).Value = Trim(txtPCountryCode.Text)
                    cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_CtyCPhone", SqlDbType.NVarChar, 15)).Value = Trim(txtCityCode.Text)
                    cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_PhoneNo", SqlDbType.NVarChar, 15)).Value = Trim(txtPhoneno.Text)
                    cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_PhoneExtn", SqlDbType.NVarChar, 15)).Value = Trim(txtExtensionno.Text)
                    cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_CCMobile", SqlDbType.NVarChar, 15)).Value = txtMCountryCode.Text.Trim
                    cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_MobileNo", SqlDbType.NVarChar, 15)).Value = Trim(txtMobileno.Text)
                    cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_EmailId", SqlDbType.NVarChar, 150)).Value = Trim(txtEmailID.Text)
                    cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_AfterSalesServiceId", SqlDbType.NVarChar, 10)).Value = RemoveLiterals(ddlServiceStation.SelectedItem.Value.Trim)
                    cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_FinancialYearId ", SqlDbType.NVarChar, 20)).Value = Trim(Session("g_FinYear").ToString)
                    cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_CompanyId", SqlDbType.NVarChar, 20)).Value = Trim(Session("g_Company").ToString)
                    cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_UserId", SqlDbType.NVarChar, 20)).Value = Trim(Session("g_User").ToString)
                    cmd.Parameters.Add(New SqlParameter("@FormName", SqlDbType.NVarChar, 100)).Value = "After Sales Service"
                    cmd.Parameters.Add(New SqlParameter("@Mode", SqlDbType.VarChar, 50)).Value = "Update"
                    If con.State = ConnectionState.Open Then ' check whether connection is opened or not
                        con.Close()
                    End If
                    con.Open()
                    cmd.ExecuteNonQuery()
                    con.Close() ' close connection
                    Fill_Combo("SELECT AfterSalesService.ASS_Kid, AfterSalesService.ASS_ServiceCenter + '  - ' + City_Master.City_Name AS ServiceStation FROM AfterSalesService INNER JOIN City_Master ON AfterSalesService.ASS_LocationId = City_Master.City_Kid WHERE (AfterSalesService.ASS_CompanyId ='" & Session("g_Company").ToString & "') AND (AfterSalesService.ASS_IsDeleted = 0) AND (AfterSalesService.ASS_SupplierId = '" & Session("SupplierID") & "') AND (AfterSalesService.ASS_UserId = '" & Session("g_User") & "')", ddlExisting)
                    con.Dispose()
                    ClearFields()
                    FillCombo()
                    ''btnAddMore.Enabled = True
                    ''BtnSave.Enabled = False
                   
                    ClearControls()
                    tblservicestationcontact.Visible = True
                    tblservicestationcontactheader.Visible = True
                    tblservicestation.Visible = False
                    tblservicestationheader.Visible = False
                    ddlASSUId.Visible = True
                    ddlAmountUnit.Visible = True
                    ddlCountry.Visible = True
                    ddlState.Visible = True
                    ddlCity.Visible = True
                    ddlExisting.Visible = True
                    CreateMessageAlert(Me, "Service Station Contact Update Successfully.", "StrKeyVal")
                    ShowMessage("Service Station Contact Update Successfully.")
                    getGridData(ddlServiceStation.SelectedValue.ToString)
                    EnableContactControls(False)
                    EditClickVisible(Me, BtnAddContact, BtnSaveContact, BtnUpdateContact, BtnDeleteContact, btnCancelContact)
                End If
            Else
                ShowMessage("Service Station Contact not found.")
            End If
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")                                 'Display the Error Message
        End Try
    End Sub

    Protected Sub BtnDeleteContact_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnDeleteContact.Click
        Try
            Dim dt As DataTable = ReturnDataTable("SELECT  AfterSalesServiceContacts.* FROM AfterSalesServiceContacts  WHERE ServiceStationContacts_Kid='" & RemoveLiterals(gvsscontact.SelectedDataKey.Value.ToString) & "' and ServiceStationContacts_IsDeleted='0'")
            If dt.Rows.Count > 0 Then
                If ddlServiceStation.SelectedIndex = 0 Then
                    lblsserror.Text = "Please Select Service Station for Adding Contact."
                    Exit Sub
                Else
                    'DvASSS.Visible = True
                    lblError.Visible = False
                    ContactGenerateCode()
                    Dim con As New SqlConnection
                    con.ConnectionString = System.Configuration.ConfigurationManager.AppSettings("ConnectionString")
                    Dim cmd As New SqlCommand
                    cmd.CommandType = CommandType.StoredProcedure
                    cmd.CommandText = "AfterSalesServiceContacts_Proc"
                    cmd.Connection = con
                    cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_Kid", SqlDbType.NVarChar, 20)).Value = RemoveLiterals(dt.Rows(0).Item("ServiceStationContacts_Kid").ToString.Trim)
                    cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_Code", SqlDbType.NVarChar, 20)).Value = RemoveLiterals(dt.Rows(0).Item("ServiceStationContacts_code").ToString.Trim)
                    cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_ContactPerson", SqlDbType.NVarChar, 100)).Value = Trim(txtContactPerson.Text.Trim)
                    cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_PersonDesignation", SqlDbType.NVarChar, 100)).Value = Trim(txtDesignation.Text.Trim)
                    cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_CCPhone", SqlDbType.NVarChar, 15)).Value = Trim(txtPCountryCode.Text)
                    cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_CtyCPhone", SqlDbType.NVarChar, 15)).Value = Trim(txtCityCode.Text)
                    cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_PhoneNo", SqlDbType.NVarChar, 15)).Value = Trim(txtPhoneno.Text)
                    cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_PhoneExtn", SqlDbType.NVarChar, 15)).Value = Trim(txtExtensionno.Text)
                    cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_CCMobile", SqlDbType.NVarChar, 15)).Value = txtMCountryCode.Text.Trim
                    cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_MobileNo", SqlDbType.NVarChar, 15)).Value = Trim(txtMobileno.Text)
                    cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_EmailId", SqlDbType.NVarChar, 150)).Value = Trim(txtEmailID.Text)
                    cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_AfterSalesServiceId", SqlDbType.NVarChar, 10)).Value = RemoveLiterals(ddlServiceStation.SelectedItem.Value.Trim)
                    cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_FinancialYearId ", SqlDbType.NVarChar, 20)).Value = Trim(Session("g_FinYear").ToString)
                    cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_CompanyId", SqlDbType.NVarChar, 20)).Value = Trim(Session("g_Company").ToString)
                    cmd.Parameters.Add(New SqlParameter("@ServiceStationContacts_UserId", SqlDbType.NVarChar, 20)).Value = Trim(Session("g_User").ToString)
                    cmd.Parameters.Add(New SqlParameter("@FormName", SqlDbType.NVarChar, 100)).Value = "After Sales Service"
                    cmd.Parameters.Add(New SqlParameter("@Mode", SqlDbType.VarChar, 50)).Value = "Delete"
                    If con.State = ConnectionState.Open Then ' check whether connection is opened or not
                        con.Close()
                    End If
                    con.Open()
                    cmd.ExecuteNonQuery()
                    CreateMessageAlert(Me, "Service Station Contact Delete Successfully.", "StrKeyVal")
                    ShowMessage("Service Station Contact Delete Successfully.")
                    con.Close() ' close connection
                    Fill_Combo("SELECT AfterSalesService.ASS_Kid, AfterSalesService.ASS_ServiceCenter + '  - ' + City_Master.City_Name AS ServiceStation FROM AfterSalesService INNER JOIN City_Master ON AfterSalesService.ASS_LocationId = City_Master.City_Kid WHERE (AfterSalesService.ASS_CompanyId ='" & Session("g_Company").ToString & "') AND (AfterSalesService.ASS_IsDeleted = 0) AND (AfterSalesService.ASS_SupplierId = '" & Session("SupplierID") & "') AND (AfterSalesService.ASS_UserId = '" & Session("g_User") & "')", ddlExisting)
                    con.Dispose()
                    ClearFields()
                    FillCombo()
                    ''btnAddMore.Enabled = True
                    ''BtnSave.Enabled = False
                    btnAddMore.Visible = True
                    BtnSave.Visible = True
                    ClearControls()
                    tblservicestationcontact.Visible = False
                    tblservicestationcontactheader.Visible = False
                    tblservicestation.Visible = True
                    tblservicestationheader.Visible = True
                    ddlASSUId.Visible = True
                    ddlAmountUnit.Visible = True
                    ddlCountry.Visible = True
                    ddlState.Visible = True
                    ddlCity.Visible = True
                    ddlExisting.Visible = True

                    getGridData(ddlServiceStation.SelectedValue.ToString)
                    DeleteClickVisible(Me, BtnAddContact, BtnSaveContact, BtnUpdateContact, BtnDeleteContact, btnCancelContact)
                End If
            Else
                ShowMessage("Service Station Contact not found.")
            End If
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")                                 'Display the Error Message
        End Try
    End Sub

    Protected Sub gvsscontact_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gvsscontact.SelectedIndexChanged
        Dim dt As DataTable = ReturnDataTable("SELECT  AfterSalesServiceContacts.* FROM AfterSalesServiceContacts  WHERE ServiceStationContacts_Kid='" & RemoveLiterals(gvsscontact.SelectedDataKey.Value.ToString) & "' and ServiceStationContacts_IsDeleted='0'")

        If dt.Rows.Count > 0 Then
            tblservicestationcontact.Visible = True
            tblservicestationcontactheader.Visible = True
            tblservicestation.Visible = False
            tblservicestationheader.Visible = False

            ddlASSUId.Visible = False
            ddlAmountUnit.Visible = False
            ddlCountry.Visible = False
            ddlState.Visible = False
            ddlCity.Visible = False
            ddlExisting.Visible = False
            Try
                txtContactPerson.Text = chkDBNull(dt.Rows(0).Item("ServiceStationContacts_ContactPerson").ToString)
                txtDesignation.Text = chkDBNull(dt.Rows(0).Item("ServiceStationContacts_PersonDesignation").ToString)
                txtPCountryCode.Text = chkDBNull(dt.Rows(0).Item("ServiceStationContacts_CCPhone").ToString)
                txtCityCode.Text = chkDBNull(dt.Rows(0).Item("ServiceStationContacts_CtyCPhone").ToString)
                txtPhoneno.Text = chkDBNull(dt.Rows(0).Item("ServiceStationContacts_PhoneNo").ToString)
                txtExtensionno.Text = chkDBNull(dt.Rows(0).Item("ServiceStationContacts_PhoneExtn").ToString)
                txtMCountryCode.Text = chkDBNull(dt.Rows(0).Item("ServiceStationContacts_CCMobile").ToString)
                txtMobileno.Text = chkDBNull(dt.Rows(0).Item("ServiceStationContacts_MobileNo").ToString)
                txtEmailID.Text = chkDBNull(dt.Rows(0).Item("ServiceStationContacts_EmailId").ToString)

                Try
                    ddlServiceStation.SelectedIndex = ddlServiceStation.Items.IndexOf(ddlServiceStation.Items.FindByValue(dt.Rows(0).Item("ServiceStationContacts_AfterSalesServiceId").ToString))
                Catch
                End Try
                'ddl_city.SelectedValue = dt.Rows(0).Item("ctm_city").ToString

                GridClickVisible(Me, BtnAddContact, BtnSaveContact, BtnUpdateContact, BtnDeleteContact, btnCancelContact)
                dt.Clear()
                If Session("AdminID") <> Nothing Or Session("AdminID") = Nothing Then
                    BtnAddContact.Visible = False
                    btnCancelContact.Visible = True
                    BtnDeleteContact.Visible = True
                    BtnUpdateContact.Visible = True
                    EnableContactControls(True)
                Else
                    BtnAddContact.Visible = True
                    btnCancelContact.Visible = False
                    BtnDeleteContact.Visible = False
                    BtnUpdateContact.Visible = False
                    EnableContactControls(False)
                End If
            Catch ex As Exception

            End Try
        End If
    End Sub

    Public Sub ShowMessage(ByVal strValue As String)
        lblError.Visible = True
        lblError.Text = strValue
    End Sub

    Private Sub EnableContactControls(ByVal bool As Boolean)
        txtContactPerson.Enabled = bool
        txtDesignation.Enabled = bool
        txtPCountryCode.Enabled = bool
        txtCityCode.Enabled = bool
        txtPhoneno.Enabled = bool
        txtExtensionno.Enabled = bool
        txtMCountryCode.Enabled = bool
        txtMobileno.Enabled = bool
        txtEmailID.Enabled = bool
        'ddlServiceStation.Enabled = bool
    End Sub

    Private Sub ClearControls()
        txtContactPerson.Text = ""
        txtDesignation.Text = ""
        txtPCountryCode.Text = ""
        txtCityCode.Text = ""
        txtPhoneno.Text = ""
        txtExtensionno.Text = ""
        txtMCountryCode.Text = ""
        txtMobileno.Text = ""
        txtEmailID.Text = ""
        'ddlServiceStation.SelectedIndex = 0
    End Sub

    Protected Sub btnCancelContact_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancelContact.Click
        If Session("AdminID") <> Nothing Or Session("AdminID") = Nothing Then
            btnUpdate.Visible = False
            btnDelete.Visible = False
        Else
        End If
        ddlExisting.SelectedIndex = -1
        ClearControls()
        EnableContactControls(False)
        gvsscontact.SelectedIndex = -1
        CancelClickVisible(Me, BtnAddContact, BtnSaveContact, BtnUpdateContact, BtnDeleteContact, btnCancelContact)
    End Sub

    Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        If Session("AdminID") <> Nothing Or Session("AdminID") = Nothing Then
            btnUpdate.Visible = False
            btnDelete.Visible = False
        Else
        End If
        ClearFields()
        EnableControls(False)
        btnAddMore.Visible = True
        BtnSave.Visible = False
        gvsscontact.SelectedIndex = -1
        ddlExisting.SelectedIndex = -1
        ddlExisting.Enabled = True
        CancelClickVisible(Me, btnAddMore, BtnSave, btnUpdate, btnDelete, btnCancel)
    End Sub

    Protected Sub btncontact_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btncontact.Click
        '        ScriptManager.RegisterClientScriptBlock(sender, sender.GetType(), "MyKey", "WebForm_AutoFocus('" + ddlServiceStation.ClientID + "');", True)
        Dim str_ddl As String
        tblservicestation.Visible = False
        tblservicestationheader.Visible = False
        ddlASSUId.Visible = False
        ddlAmountUnit.Visible = False
        ddlCountry.Visible = False
        ddlState.Visible = False
        ddlCity.Visible = False
        ddlExisting.Visible = False
        tblservicestationcontact.Visible = True
        tblservicestationcontactheader.Visible = True
        ClearControls()

        ddlServiceStation.ClearSelection()
        If ddlExisting.SelectedIndex > 0 Then
            ddlServiceStation.Items.FindByText(RemoveLiterals(ddlExisting.SelectedItem.Text.ToString)).Selected = True
            ddlServiceStation.Enabled = False
        Else
            If hf1.Value <> "" And hf2.Value <> "" Then
                str_ddl = hf1.Value.ToString & "  - " & hf2.Value.ToString
                ddlServiceStation.Items.FindByText(RemoveLiterals(str_ddl.ToString)).Selected = True
                ddlServiceStation.Enabled = False
            Else
                ddlServiceStation.Enabled = True
            End If
        End If

        EnableContactControls(False)
        BtnAddContact.Visible = True
        BtnSaveContact.Visible = False
        btnCancelContact.Visible = False
        hf1.Value = ""
        hf2.Value = ""
    End Sub

    Protected Sub btnclose_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnclose.Click
        tblservicestationcontact.Visible = False
        tblservicestationcontactheader.Visible = False
        tblservicestation.Visible = True
        tblservicestationheader.Visible = True
        ddlASSUId.Visible = True
        ddlAmountUnit.Visible = True
        ddlCountry.Visible = True
        ddlState.Visible = True
        ddlCity.Visible = True
        ddlExisting.Visible = True
        'btnAddMore.Visible = True
        BtnSave.Visible = False

        If ddlExisting.SelectedIndex > 0 Then
            If Session("AdminID") <> Nothing Or Session("AdminID") = Nothing Then
                btnAddMore.Visible = False
                EnableControls(True)
                rblType.Enabled = False
            Else
                EnableControls(False)
            End If
        Else
            btnAddMore.Visible = True
            'btnsave.Visible=True 
            EnableControls(False)
        End If
        hf1.Value = ""
        hf2.Value = ""
    End Sub

    Protected Sub btnBack_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Response.Redirect("other-details.aspx")
    End Sub

    Protected Sub ddlCountry_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlCountry.SelectedIndexChanged
        Try
            Fill_Combo("SELECT State_Master.State_Kid, State_Master.State_Name, Country_Master.Country_Name FROM Country_Master INNER JOIN State_Master ON Country_Master.Country_Kid = State_Master.State_CountryId WHERE State_Master.State_CompanyId = '" & Session("g_Company").ToString & "' AND State_Master.State_IsDeleted = '0' AND Country_Master.Country_Kid = '" & ddlCountry.SelectedValue & "'", ddlState)
            ddlCity.Items.Clear()
            'ScriptManager.RegisterClientScriptBlock(sender, sender.GetType(), "MyKey", "WebForm_AutoFocus('" + ddlState.ClientID + "');", True)

        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")     'Display the Error Message
        End Try
    End Sub

    Protected Sub ddlState_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlState.SelectedIndexChanged
        Try
            ddlCity.Items.Clear()
            'Fill_Combo("SELECT distinct City_Master.City_Kid, City_Master.City_Name, State_Master.State_Name, City_Master.City_CompanyId FROM City_Master INNER JOIN  State_Master ON City_Master.City_StateId = State_Master.State_Kid WHERE City_Master.City_IsDeleted = '0' AND City_Master.City_CompanyId = '" & Session("g_Company").ToString & "' AND State_Master.State_Kid = '" & ddlState.SelectedValue & "'", ddlCity)
            'ddlCity.Items.Add("Others")
            Fill_Combo("SELECT distinct City_Master.City_Kid, City_Master.City_Name, State_Master.State_Name, City_Master.City_CompanyId FROM City_Master INNER JOIN  State_Master ON City_Master.City_StateId = State_Master.State_Kid WHERE City_Master.City_IsDeleted = '0' AND City_Master.City_CompanyId = '" & Session("g_Company").ToString & "' AND State_Master.State_Kid = '" & ddlState.SelectedValue & "' order by City_Master.City_Name", ddlCity)
            'ScriptManager.RegisterClientScriptBlock(sender, sender.GetType(), "MyKey", "WebForm_AutoFocus('" + ddlCity_Code.ClientID + "');", True)
            ddlCity.Enabled = True
            'ddlCity.Attributes.Add("onchange", "return checkCityddl(this,'" & ddlState.SelectedItem.Value.ToString & "','" & Session("g_Company").ToString & "','" & Session("g_User") & "','" & Session("g_FinYear") & "');")
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")     'Display the Error Message
        End Try
    End Sub

    Protected Sub iCLose_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles iCLose.Click
        tblservicestation.Visible = True
        tblservicestationheader.Visible = True
        ddlASSUId.Visible = True
        ddlAmountUnit.Visible = True
        ddlCountry.Visible = True
        ddlState.Visible = True
        ddlCity.Visible = True
        ddlExisting.Visible = True
        tblservicestationcontact.Visible = False
        tblservicestationcontactheader.Visible = False
        hf1.Value = ""
        hf2.Value = ""
    End Sub

    Protected Sub ddlServiceStation_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlServiceStation.SelectedIndexChanged
        If ddlServiceStation.SelectedIndex > 0 Then
            If Session("AdminID") <> Nothing Or Session("AdminID") = Nothing Then
                EnableControls(True)
                btnAddMore.Visible = False
                btnUpdate.Visible = True
                btnDelete.Visible = True
            Else
                EnableControls(False)
                btnAddMore.Visible = True
            End If
        Else
            BtnAddContact.Visible = True
            BtnUpdateContact.Visible = False
            BtnDeleteContact.Visible = False
            btnCancelContact.Visible = False
        End If
        getGridData(ddlServiceStation.SelectedValue.ToString)
        ClearControls()
        ''BtnSave.Enabled = False
        ''btnAddMore.Enabled = True
        BtnSave.Visible = False

        'Else
        'EnableControls(False)
        'ClearFields()
        'End If
    End Sub

    Protected Sub gvsscontact_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs)
        gvsscontact.PageIndex = e.NewPageIndex

        If ddlServiceStation.SelectedIndex > 0 Then
            getGridData(ddlServiceStation.SelectedValue.ToString)
        ElseIf ddlExisting.SelectedIndex > 0 Then
            getGridData(ddlExisting.SelectedValue.ToString)
        Else
            getGridData(ddlExisting.SelectedItem.ToString)
        End If

    End Sub

End Class
