'-----------------------------------------------------------------
'<copyright file="CategoryMaster.aspx.vb" company="Kimaya" >
'   Copyright(c) Kimaya Ltd. All rights reserved.
'</copyright>
'<Desc>
'   Codebehind file for CategoryMaster.aspx used for Bank_Master
'</Desc>
'<DateOfCreation>
'   21/06/07
'</DateOfCreation>
'<Developer>
'  Neeta 
'</Developer>
'-----------------------------------------------------------------
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Collections
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.IO
Imports ModCommon
Partial Class CategoryMaster
    Inherits System.Web.UI.Page
    Shared Search As Boolean
    Shared g_User As String
    Shared g_Company As String
    Shared value1 As String
    Shared value2 As String
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            If (Not IsPostBack) Then

                lblParentCategoryName.Visible = False
                value1 = ""
                value2 = ""
                ClearFields()               'Clear the TextFields
                UnLockTextBox(False)        'Unlock (Enable) TextFields
                g_User = "U1"
                g_Company = "COM1"
                'g_User = Session("g_User").ToString
                'g_Company = Session("g_Company").ToString
                FillCombo()
                FillGrid("")                  'Fills the DatagGrid with All Records
                Call CancelClick(Me, BtnAdd, BtnSave, BtnEdit, BtnDelete, BtnCancel, BtnSearch)
                Search = False              'Default Value for Search Mode
                Call CheckRights(Me, g_User, "Category Master")
            End If
            txtCategoryCode.MaxLength = 20 : txtCategoryName.MaxLength = 50
            txtCategoryName.Attributes.Add("onblur", "return CheckNull('txtCategoryName');")
            txtCategoryName.Attributes.Add("onkeypress", "return BlockNumericValue(event);")

        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")
        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

    '----------------------------------------------------------------------------------------------------------------------------
    '<UserDefinedFunction Name="ClearFields">
    '   <Desc> For Clearing the contents of TextFields </Desc>
    '   <Input> Nothing </Input>
    '   <Output> Nothing </Output>
    '   <DateOfCreation> 21/06/06 </DateOfCreation>
    '   <Developer> Neeta </Developer>
    '</UserDefinedFunction>
    '----------------------------------------------------------------------------------------------------------------------------
    Protected Sub ClearFields()
        Try
            txtCategoryCode.Text = ""                           'Assign Null to the TextField
            txtCategoryName.Text = ""
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")     'Display the Error Message
        End Try
    End Sub

    '----------------------------------------------------------------------------------------------------------------------------
    '<UserDefinedFunction Name="UnLockTextBox">
    '   <Desc> For Locking & UnLocking the TextFields </Desc>
    '   <Input> 
    '   <Param Name="Action">
    '   True or False
    '   </Param>
    '   </Input>
    '   <Output> Nothing </Output>
    '   <DateOfCreation> 21/06/06 </DateOfCreation>
    '   <Developer> Neeta </Developer>
    '</UserDefinedFunction>
    '----------------------------------------------------------------------------------------------------------------------------
    Protected Sub UnLockTextBox(ByVal Action As Boolean)
        Try
            'txtBankCode.Enabled = Action                    'Enable / Disable the TextField
            txtCategoryName.Enabled = Action                    'Enable / Disable the TextField
            ddlCM1.Enabled = Action
            ddlCM2.Enabled = Action
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")     'Display the Error Message
        End Try
    End Sub

    '----------------------------------------------------------------------------------------------------------------------------
    '<UserDefinedFunction Name="FillGrid">
    '   <Desc> To Fill the Grid with All Records </Desc>
    '   <Input> 
    '  <Param Name="PTN">
    '   PartType_Name
    '   </Param>
    '   </Input>
    '   <Output> Nothing </Output>
    '   <DateOfCreation> 21/06/06 </DateOfCreation>
    '   <Developer> Neeta </Developer>
    '</UserDefinedFunction>
    '----------------------------------------------------------------------------------------------------------------------------
    Protected Sub FillGrid(ByVal PTN As String)
        Try

            Dim qry As String                                   'Define a String Variable for Query
            Dim con As New SqlConnection                        'Define connection variable for connecting to SQL-Server
            con.ConnectionString = System.Configuration.ConfigurationManager.AppSettings("ConnectionString")    'Read the ConnectionString from web.config File
            con.Open()                                          'Open the Connection
            If Trim(PTN) = "" Then
                qry = "SELECT Category_Master.Category_Code [Code], Category_Master_1.Category_Name [Category], Category_Master.Category_Kid [Kid], Category_Master.Category_Name [Expr1],Category_Master_1.Category_ParentId  [Pid], Category_Master.Category_ParentId  [Expr2] FROM  Category_Master , Category_Master AS Category_Master_1 where Category_Master.Category_ParentId = Category_Master_1.Category_Kid and Category_Master.Category_Isdeleted='0'"
            End If
            gvCategory.Columns(1).Visible = True
            gvCategory.Columns(5).Visible = True
            gvCategory.Columns(6).Visible = True
            Dim cmd As New SqlCommand(qry, 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
            gvCategory.DataSource = dr                          'Set the DataReader Variable as DataSource for the Grid
            gvCategory.DataBind()                               'Bind the Data to the Grid
            gvCategory.Columns(1).Visible = False
            gvCategory.Columns(5).Visible = False
            gvCategory.Columns(6).Visible = False
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")     'Display the Error Message
        End Try
    End Sub

    Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnAdd.Click
        Try
            'If CBool(Session("Add_Flag").ToString) = False Then
            '    CreateMessageAlert(Me, "You Do Not Have Access Right To Add New Record !", "StrKeyVal")  'Display the Message 
            '    Exit Sub
            'End If
            ClearFields()                                       'Clears the TextFields
            UnLockTextBox(True)                                 'Enable the TextFields
            Call AddClick(Me, BtnAdd, BtnSave, BtnEdit, BtnDelete, BtnCancel, BtnSearch)
            Call GenerateBankCode()
            txtCategoryName.Focus()                                 'Put the Focus to BankCode TextField
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")     'Display the Error Message
        End Try
    End Sub

    Protected Sub gvgvCategory_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gvCategory.SelectedIndexChanged
        Try
            lblParentCategoryName.Visible = True
            Dim str, str1, parent As String
            txtCategoryId.Text = gvCategory.SelectedRow.Cells(1).Text     'Assign the value of cell to the textField
            txtCategoryCode.Text = gvCategory.SelectedRow.Cells(2).Text     'Assign the value of cell to the textField
            txtCategoryName.Text = gvCategory.SelectedRow.Cells(3).Text
            str1 = gvCategory.SelectedRow.Cells(4).Text
            str = gvCategory.SelectedRow.Cells(4).Text
            parent = ""
            While parent <> "Root Categ"
                If parent = "" Then
                    parent = getparentcategory(gvCategory.SelectedRow.Cells(4).Text)
                Else
                    str = parent & ">" & str
                    parent = getparentcategory(parent)
                End If
            End While
            'Label1.Text = str
            lblParentCategoryName.Text = str & ">" & gvCategory.SelectedRow.Cells(3).Text
            UnLockTextBox(True)                                             'Enable the TextFields
            Call GridClick(Me, BtnAdd, BtnSave, BtnEdit, BtnDelete, BtnCancel, BtnSearch)
            Search = False
            FillCombo()
            txtCategoryName.Focus()
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")                 'Display the Error Message
        End Try
    End Sub
    Protected Function getparentcategory(ByVal str As String)
        Dim con As New SqlConnection
        Dim cmd As New SqlCommand
        Dim str1, str2 As String
        con.ConnectionString = System.Configuration.ConfigurationManager.AppSettings("ConnectionString")
        cmd.Connection = con
        cmd.CommandText = "SELECT Category_Master_1.Category_Name FROM Category_Master,Category_Master AS Category_Master_1 where Category_Master.Category_ParentId = Category_Master_1.Category_Kid and Category_Master.Category_Name = '" & str & "'"
        str2 = ReturnValue("SELECT Category_Master_1.Category_Name FROM Category_Master,Category_Master AS Category_Master_1 where Category_Master.Category_ParentId = Category_Master_1.Category_Kid and Category_Master.Category_Name = '" & str & "' ")
        con.Open()
        If (str2 = "") Then
            Return "Root Categ"
            con.Close()
        Else
            str1 = cmd.ExecuteScalar()
            con.Close()
            Return str1
        End If
    End Function
    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnSave.Click
        Try
            'If CBool(Session("Add_Flag").ToString) = False Then
            '    CreateMessageAlert(Me, "You Do Not Have Access Right To Add New Record !", "StrKeyVal")  'Display the Message 
            '    Exit Sub
            'End If

            If Trim(txtCategoryCode.Text) = "" Then                                         'If txtPartTypeCode TextField is Null then
                CreateMessageAlert(Me, "Category Code Cannot be Null !", "StrKeyVal")      'Display the Message 
                Exit Sub
            End If
            If Trim(txtCategoryName.Text) = "" Then                                         'If txtPartTypeName TextField is Null then
                CreateMessageAlert(Me, " New Category  Cannot be Null !", "StrKeyVal")      'Display the Message
                Exit Sub
            End If

            If Trim(ddlCM1.SelectedValue) = "" Then                                         'If txtPartTypeName TextField is Null then
                CreateMessageAlert(Me, "Category Name Cannot be Null !", "StrKeyVal")      'Display the Message
                Exit Sub
            End If

            Dim con As New SqlConnection                                                    'Define connection variable for connecting to SQL-Server
            con.ConnectionString = System.Configuration.ConfigurationManager.AppSettings("ConnectionString")    'Read the ConnectionString from web.config File
            con.Open()                                                                       'Open the Connection
            If IsAlreadyPresent("select count(*) from Category_Master where Category_Code='" & txtCategoryCode.Text.Trim & "'and Category_isdeleted='0' and Category_companyId='" & g_Company & "'") Then  ' To Check Existance of Engineer Code
                CreateMessageAlert(Me, " Category Code Already Present !", "StrKeyVal")      'Display the Message
                txtCategoryCode.Text = "" : txtCategoryCode.Focus()
                Exit Sub
            End If
            'If IsAlreadyPresent("select count(*) from Category_Master where Category_Name='" & txtCategoryName.Text.Trim & "'and Category_isdeleted='0' and Category_companyId='" & g_Company & "'") Then  ' To Check Existance of Engineer Code
            '    CreateMessageAlert(Me, " Category Name Already Present !", "StrKeyVal")      'Display the Message
            '    txtCategoryName.Text = "" : txtCategoryName.Focus()
            '    Exit Sub
            'End If

            Dim cmd As New SqlCommand                                                       'Define command variable to execute the query
            cmd.CommandType = CommandType.StoredProcedure                                   'Set the Command Type to Stored procedure
            cmd.CommandText = "Category_Master_Proc"                                        'Assign the Name of Stored Procedure, to Execute
            cmd.Connection = con                                                            'Assign the connection
            cmd.Parameters.Add(New SqlParameter("@Category_Kid", SqlDbType.NVarChar, 20)).Value = Trim(txtCategoryId.Text)       'Add Parameter Category_Kid and assign the value of txtCategoryId TextField  to it
            cmd.Parameters.Add(New SqlParameter("@Category_Code", SqlDbType.NVarChar, 20)).Value = Trim(txtCategoryCode.Text)       'Add Parameter Category_Code and assign the value of txtCategoryCode TextField to it
            cmd.Parameters.Add(New SqlParameter("@Category_Name", SqlDbType.NVarChar, 25)).Value = Trim(txtCategoryName.Text)       'Add Parameter Category_Name and assign the value of txtCategoryName TextField to it
            If ddlCM1.SelectedItem.Text = "Select" Then
                cmd.Parameters.Add(New SqlParameter("@Category_ParentId", SqlDbType.NVarChar, 20)).Value = ddlCM2.SelectedValue       'tvCategory.SelectedNode.Text      'Trim(ddlParentCategory.SelectedValue)       'Add Parameter Category_Code and assign the value of txtCategoryCode TextField to it
            Else
                cmd.Parameters.Add(New SqlParameter("@Category_ParentId", SqlDbType.NVarChar, 20)).Value = ddlCM1.SelectedValue        'tvCategory.SelectedNode.Text      'Trim(ddlParentCategory.SelectedValue)       'Add Parameter Category_Code and assign the value of txtCategoryCode TextField to it
            End If
            cmd.Parameters.Add(New SqlParameter("@Category_CompanyId", SqlDbType.NVarChar, 20)).Value = Trim(g_Company)       'Add Parameter Category_CompanyId and assign the value of Session("g_Company") to it
            cmd.Parameters.Add(New SqlParameter("@Category_UserId", SqlDbType.NVarChar, 20)).Value = Trim(g_User)             'Add Parameter UserCode and assign the value of Session("g_User").toString to it
            cmd.Parameters.Add(New SqlParameter("@FormName", SqlDbType.NVarChar, 100)).Value = "Category Master"                           'Add Parameter FormName and assign the name of form to it
            cmd.Parameters.Add(New SqlParameter("@Mode", SqlDbType.VarChar, 50)).Value = "Insert"                                   'Add Parameter Mode and assign the DML Operation to Execute (Insert)
            cmd.ExecuteNonQuery()                                                           'Execute the Query
            FillGrid("")                                                                      'Fill the Grid
            CreateMessageAlert(Me, "Record Saved Successfully...", "StrKeyVal")             'Display the Message
            FillCombo()
            Label1.Text = ""
            ClearFields()                                                                   'Clear the TextFields
            UnLockTextBox(False)                                                            'Disable the TextFields
            Call SaveClick(Me, BtnAdd, BtnSave, BtnEdit, BtnDelete, BtnCancel, BtnSearch)
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")                                 'Display the Error Message
        End Try
    End Sub

    Protected Sub btnEdit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnEdit.Click
        Try
            'If CBool(Session("Modify_Flag").ToString) = False Then
            '    CreateMessageAlert(Me, "You Do Not Have Access Right To Modify An Existing Record !", "StrKeyVal")  'Display the Message 
            '    Exit Sub
            'End If
            If Trim(txtCategoryCode.Text) = "" Then                                         'If txtPartTypeCode TextField is Null then
                CreateMessageAlert(Me, "Category Code Cannot be Null !", "StrKeyVal")      'Display the Message 
                Exit Sub
            End If
            If Trim(txtCategoryName.Text) = "" Then                                         'If txtPartTypeName TextField is Null then
                CreateMessageAlert(Me, " New Category  Cannot be Null !", "StrKeyVal")      'Display the Message 
                Exit Sub
            End If
            If Trim(ddlCM1.SelectedValue) = "" Then                                         'If txtPartTypeName TextField is Null then
                CreateMessageAlert(Me, "Category Name Cannot be Null !", "StrKeyVal")      'Display the Message
                Exit Sub
            End If


            If IsAlreadyPresent("select count(*) from Category_Master where Category_code!='" & Trim(txtCategoryCode.Text) & "' and  Category_Name='" & txtCategoryName.Text.Trim & "'  and Category_isdeleted='0' and Category_companyId='" & g_Company & "'") Then  ' To Check Existance of Engineer Code
                CreateMessageAlert(Me, " Category Name Already Present !", "StrKeyVal")      'Display the Message
                txtCategoryName.Text = "" : txtCategoryName.Focus()
                Exit Sub
            End If

            Dim con As New SqlConnection                                                    'Define connection variable for connecting to SQL-Server
            con.ConnectionString = System.Configuration.ConfigurationManager.AppSettings("ConnectionString")    'Read the ConnectionString from web.config File
            con.Open()                                                                      'Open the Connection
            Dim cmd As New SqlCommand                                                       'Define command variable to execute the query
            cmd.CommandType = CommandType.StoredProcedure                                   'Set the Command Type to Stored procedure
            cmd.CommandText = "Category_Master_Proc"                                        'Assign the Name of Stored Procedure, to Execute
            cmd.Connection = con                                                            'Assign the connection

            cmd.Parameters.Add(New SqlParameter("@Category_Kid", SqlDbType.NVarChar, 20)).Value = Trim(txtCategoryId.Text)       'Add Parameter Category_Kid and assign the value of txtCategoryId TextField   to it
            cmd.Parameters.Add(New SqlParameter("@Category_Code", SqlDbType.NVarChar, 20)).Value = Trim(txtCategoryCode.Text)       'Add Parameter Category_Code and assign the value of txtCategoryCode TextField to it
            cmd.Parameters.Add(New SqlParameter("@Category_Name", SqlDbType.NVarChar, 25)).Value = Trim(txtCategoryName.Text)       'Add ParameterCategory_Name and assign the value of txtCategoryName TextField to it
            If ddlCM1.SelectedItem.Text = "Select" Then
                cmd.Parameters.Add(New SqlParameter("@Category_ParentId", SqlDbType.NVarChar, 20)).Value = ddlCM2.SelectedValue       'tvCategory.SelectedNode.Text      'Trim(ddlParentCategory.SelectedValue)       'Add Parameter Category_Code and assign the value of txtCategoryCode TextField to it
            Else
                cmd.Parameters.Add(New SqlParameter("@Category_ParentId", SqlDbType.NVarChar, 20)).Value = ddlCM1.SelectedValue        'tvCategory.SelectedNode.Text      'Trim(ddlParentCategory.SelectedValue)       'Add Parameter Category_Code and assign the value of txtCategoryCode TextField to it
            End If
            cmd.Parameters.Add(New SqlParameter("@Category_CompanyId", SqlDbType.NVarChar, 20)).Value = Trim(g_Company)       'Add Parameter Category_CompanyId and assign the value of Session("g_Company") to it
            cmd.Parameters.Add(New SqlParameter("@Category_UserId", SqlDbType.NVarChar, 20)).Value = Trim(g_User)             'Add Parameter UserCode and assign the value of Session("g_User").toString to it
            cmd.Parameters.Add(New SqlParameter("@FormName", SqlDbType.NVarChar, 100)).Value = "Category Master"
            cmd.Parameters.Add(New SqlParameter("@Mode", SqlDbType.VarChar, 50)).Value = "Update"                                   'Add Parameter Mode and assign the DML Operation to Execute (Update)
            cmd.ExecuteNonQuery()                                                           'Execute the Query
            FillGrid("")                                                                      'Fill the Grid
            CreateMessageAlert(Me, "Record Modified Successfully...", "StrKeyVal")             'Display the Message
            FillCombo()
            Label1.Text = ""
            lblParentCategoryName.Text = ""
            ClearFields()                                                                   'Clear the TextFields
            UnLockTextBox(False)                                                            'Disable the TextFields
            Call EditClick(Me, BtnAdd, BtnSave, BtnEdit, BtnDelete, BtnCancel, BtnSearch)
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")                                 'Display the Error Message
        End Try

    End Sub

    Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnDelete.Click
        Try
            'If CBool(Session("Delete_Flag").ToString) = False Then
            '    CreateMessageAlert(Me, "You Do Not Have Access Right To Delete An Existing Record !", "StrKeyVal")  'Display the Message 
            '    Exit Sub
            'End If
            If Trim(txtCategoryCode.Text) = "" Then                                         'If txtPartTypeCode TextField is Null then
                CreateMessageAlert(Me, "Category Code Cannot be Null !", "StrKeyVal")      'Display the Message 
                txtCategoryCode.Focus()
                Exit Sub
            End If
            If Trim(txtCategoryName.Text) = "" Then                                         'If txtPartTypeName TextField is Null then
                CreateMessageAlert(Me, "New Category  Cannot be Null !", "StrKeyVal")      'Display the Message 
                txtCategoryName.Focus()
                Exit Sub
            End If
            If Trim(ddlCM1.SelectedValue) = "" Then                                         'If txtPartTypeName TextField is Null then
                CreateMessageAlert(Me, "Category Name Cannot be Null !", "StrKeyVal")      'Display the Message
                Exit Sub
            End If


            'If IsAlreadyPresent("select count(*) from Category_Master where Category_Code='" & txtCategoryCode.Text.Trim & "'and Category_isdeleted='0' and Category_companyId='" & g_Company & "'") Then  ' To Check Existance of Engineer Code
            '    CreateMessageAlert(Me, " Unable to Delete, Referenced to Other Records... !", "StrKeyVal")      'Display the Message
            '    btnCancel_Click(sender, e)
            '    Exit Sub
            'End If
            Dim con As New SqlConnection                                                    'Define connection variable for connecting to SQL-Server
            con.ConnectionString = System.Configuration.ConfigurationManager.AppSettings("ConnectionString")    'Read the ConnectionString from web.config File
            con.Open()                                                                      'Open the Connection
            Dim cmd As New SqlCommand                                                       'Define command variable to execute the query
            cmd.CommandType = CommandType.StoredProcedure                                   'Set the Command Type to Stored procedure
            cmd.CommandText = "Category_Master_Proc"                                        'Assign the Name of Stored Procedure, to Execute
            cmd.Connection = con                                                            'Assign the connection

            cmd.Parameters.Add(New SqlParameter("@Category_Kid", SqlDbType.NVarChar, 20)).Value = Trim(txtCategoryId.Text)       'Add Parameter Category_Kid and assign the value of txtCategoryId  TextField to it
            cmd.Parameters.Add(New SqlParameter("@Category_Code", SqlDbType.NVarChar, 20)).Value = Trim(txtCategoryCode.Text)       'Add Parameter Category_Code and assign the value of txtCategoryCode TextField to it
            cmd.Parameters.Add(New SqlParameter("@Category_Name", SqlDbType.NVarChar, 25)).Value = Trim(txtCategoryName.Text)       'Add Parameter Category_Name and assign the value of txtCategoryName TextField to it
            If ddlCM1.SelectedItem.Text = "Select" Then
                cmd.Parameters.Add(New SqlParameter("@Category_ParentId", SqlDbType.NVarChar, 20)).Value = ddlCM2.SelectedValue       'tvCategory.SelectedNode.Text      'Trim(ddlParentCategory.SelectedValue)       'Add Parameter Category_Code and assign the value of txtCategoryCode TextField to it
            Else
                cmd.Parameters.Add(New SqlParameter("@Category_ParentId", SqlDbType.NVarChar, 20)).Value = ddlCM1.SelectedValue        'tvCategory.SelectedNode.Text      'Trim(ddlParentCategory.SelectedValue)       'Add Parameter Category_Code and assign the value of txtCategoryCode TextField to it
            End If
            cmd.Parameters.Add(New SqlParameter("@Category_CompanyId", SqlDbType.NVarChar, 20)).Value = Trim(g_Company)       'Add Parameter Category_CompanyId and assign the value of Session("g_Company") to it
            cmd.Parameters.Add(New SqlParameter("@Category_UserId", SqlDbType.NVarChar, 20)).Value = Trim(g_User)             'Add Parameter UserCode and assign the value of Session("g_User").toString to it
            cmd.Parameters.Add(New SqlParameter("@FormName", SqlDbType.NVarChar, 100)).Value = "Category Master"
            cmd.Parameters.Add(New SqlParameter("@Mode", SqlDbType.VarChar, 50)).Value = "Delete"                                   'Add Parameter Mode and assign the DML Operation to Execute (Delete)
            cmd.ExecuteNonQuery()                                                           'Execute the Query
            FillGrid("")                                                                      'Fill the Grid
            CreateMessageAlert(Me, "Record Deleted Successfully...", "StrKeyVal")             'Display the Message
            FillCombo()
            ClearFields()                                                                   'Clear the TextFields
            Label1.Text = ""
            lblParentCategoryName.Text = ""
            UnLockTextBox(False)                                                            'Disable the TextFields
            Call DeleteClick(Me, BtnAdd, BtnSave, BtnEdit, BtnDelete, BtnCancel, BtnSearch)
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")                                 'Display the Error Message
        End Try

    End Sub

    Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnCancel.Click
        Try
            ClearFields()                                       'Clears the TextFields
            UnLockTextBox(False)                                'Disable the TextFields
            Search = False
            txtCategoryName.AutoPostBack = False
            Call FillGrid("")
            Call CancelClick(Me, BtnAdd, BtnSave, BtnEdit, BtnDelete, BtnCancel, BtnSearch)
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")     'Display the Error Message
        End Try
    End Sub

    Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnSearch.Click
        Search = True                                       'Set Search Mode True
        Call SearchClick(Me, BtnAdd, BtnSave, BtnEdit, BtnDelete, BtnCancel, BtnSearch)
        txtCategoryName.Enabled = True
        txtCategoryName.AutoPostBack = True
        'Enable txtPartTypeName TextField
        'Call txtBankName_TextChanged(sender, e)
        txtCategoryName.Focus()                             'Set Focus to txtPartTypeName TextField
    End Sub

    Protected Sub txtCategoryName_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtCategoryName.TextChanged
        If Search = True Then                               'If Search Mode is true then
            Call FillGrid(Trim(txtCategoryName.Text))  'Fill the Grid filtering on txtStockLocationName 
        End If
        If BtnSave.Enabled Then BtnSave.Focus()
    End Sub
    Protected Sub GenerateBankCode()
        Try
            Dim i As String
            Dim qry As String
            Dim code As String
            txtCategoryId.Text = NewPrimaryKey(Me)
            i = "1"
            i = Format(Val(i), "000")
            While True
                code = "CTG" & "/" & Year(Date.Today) & "/" & Format(Month(Date.Today), "00") & "/" & Day(Date.Today) & "/" & i
                qry = "select count(*) from Category_Master where Category_Code='" & code & "'"
                If IsAlreadyPresent(qry) Then
                    i = Val(i) + 1
                    i = Format(Val(i), "000")
                Else
                    txtCategoryCode.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


    Sub Node_Populate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.TreeNodeEventArgs)
        If e.Node.ChildNodes.Count = 0 Then
            Select Case (e.Node.Depth)
                Case 0

                    FillModule(e.Node, "2")

                    Exit Sub
                Case 1

                    FillMenu(e.Node)

                    Exit Sub

                Case 2

                    FillSubMenu(e.Node)

                    Exit Sub

            End Select

        End If

    End Sub
    Private Sub FillCombo()
        Fill_Combo_Category("Select Category_Kid,Category_Name from Category_Master where Category_IsDeleted='0'and Category_CompanyID='" & g_Company & "' and Category_ParentId='Root Categ' order by Category_Name", ddlCM1)
    End Sub
    Public Sub Fill_Combo_Category(ByVal strQuery As String, ByVal ddl As DropDownList)
        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  
            ddl.Items.Insert(0, New ListItem("Root Category", "Root Category"))     ' Insert Blank Row at index 0  

            For i = 0 To DT.Rows.Count - 1
                ddl.Items.Insert(i + 1, 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.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 ddlCM1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        If ddlCM1.SelectedItem.Text <> "Select" Then

            If HasCategory(ddlCM1.SelectedValue) Then

                Label1.Text = value2 & ddlCM1.SelectedItem.Text & ">"
                value1 = Label1.Text
                Fill_Combo("SELECT  Category_Kid, Category_Name FROM Category_Master WHERE Category_ParentId = '" & ddlCM1.SelectedValue & "'", ddlCM2)

            Else
                Session("Product") = ddlCM1.SelectedValue
                Response.Redirect("test.aspx")
            End If
        End If
    End Sub
    Protected Function HasCategory(ByVal key As String) As Boolean
        Dim ans As String
        Dim Con As New SqlConnection
        Con.ConnectionString = System.Configuration.ConfigurationManager.AppSettings("ConnectionString")

        Dim qry As String
        qry = "SELECT  Category_ParentId FROM Category_Master WHERE Category_Kid = '" & key & "'"
        Dim cmd As New SqlCommand(qry, Con)
        Con.Open()
        If IsDBNull(cmd.ExecuteScalar) Then
            ans = ""
        Else
            ans = cmd.ExecuteScalar
        End If
        Con.Close()
        If ans = "" Then
            Return False
        Else
            Return True
        End If
    End Function

    Protected Sub ddlCM2_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        If ddlCM2.SelectedItem.Text <> "Select" Then
            If HasCategory(ddlCM2.SelectedValue) Then
                Label1.Text = value1 & ddlCM2.SelectedItem.Text & ">"
                value2 = Label1.Text
                Fill_Combo("SELECT   Category_Kid, Category_Name FROM Category_Master WHERE Category_ParentId = '" & ddlCM2.SelectedValue & "'", ddlCM1)
            End If
        End If
    End Sub
End Class