Imports System.Data
Imports System.Data.SqlClient
Partial Class Buyer_BillDetails
    Inherits System.Web.UI.Page

    Dim dt As New DataTable
    Dim dtMultiple As New DataTable
    Shared prodtable As New DataTable
    Dim intId As Integer
    Dim objPL As New BillingPL()
    Dim ds As New DataSet
    Dim query As String = ""
    Dim MultipleShipTable As New DataTable  ' Dyanemic table for Multiple  shipping 
    Dim SingleShipTable As New DataTable        ' Dyanemic table for single shipping
    Shared drow As DataRow
    Dim dc As DataColumn
    Dim dtTemp As New DataTable
    Dim dcbound As BoundField
    Dim row As GridViewRow
    Dim flag As Boolean = False
    Dim drsearch As DataRow()               ' this is for find product are presend in dropdownlist1
    Dim drsearch1 As DataRow()              ' this is for find product are presend in dropdownlist1
    Dim i As Integer = 0.0
    Dim quantity As Integer = 0.0
    Dim quantity1 As Integer = 0
    Dim netAmount As Decimal = 0.0
    Public Shared amount As Decimal = 0.0
    Dim Taxtable As New DataTable           ' this dynamic table to fetch tax information
    Dim vattable As New DataTable           ' this dynamic table to fetch Vat information

    Dim Con As New SqlConnection(ConfigurationManager.AppSettings("ConnectionString"))

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
     
        If Page.IsPostBack = False Then
            amount = 0.0
            Dim row As DataRow
            If Not ds.Tables("UserShopCart") Is Nothing Then  ' 
                ds.Tables("UserShopCart").Clear()
            End If
            cmd = New SqlCommand("getShopCart", con)
            cmd.CommandType = CommandType.StoredProcedure
            cmd.Parameters.AddWithValue("@ShopCart_BuyerUserId", Session("BuyID"))
            If con.State = ConnectionState.Open Then
                con.Close()
            End If
            da = New SqlDataAdapter(cmd)
            da.Fill(ds, "UserShopCart")     ' fill the UserShopCart table from getshopcart procedure
            If ds.Tables("UserShopCart").Rows.Count = 0 Then
                'Server.Transfer("../new_buyers/trybuyer.aspx")
            Else
                For i = 0 To ds.Tables("UserShopCart").Rows.Count - 1
                    amount = amount + ds.Tables("UserShopCart").Rows(i).Item("ShopCart_NetAmount")
                Next

                dgBill.Columns(6).Visible = True
                dgBill.Columns(7).Visible = True

                dgBill.DataSource = ds.Tables("UserShopCart")
                dgBill.DataBind()       ' bind the grid for all item in shop cart 

                singlshiptable()        ' function to fill the singleship table datatable for single shipping
                Session("SingleShippTabel") = SingleShipTable ' applied singleship tabel to session

                dgBill.Columns(6).Visible = False
                dgBill.Columns(7).Visible = False

                getAddress("1")         ' function to bind the billing addres to lblAddress
                checkOrderQty(ds.Tables("UserShopCart")) ' this function is for show control.
            End If
            rowTax.Visible = False              ' invisible  the row to hide the grid for tax.
            ' rowOctroi.Visible = False            ' invisible  the row to hide the grid for octroi.
            ' rowTable1.Visible = False    
            'rowLocation.Visible = False          ' invisible  the row to hide the grid for Location
            'rowMultipleShip.Visible = False     ' invisible  the row to hide the grid for Multiship 
            dtMultiple = dtMultipleTemp()       ' Function to create MultiShipTable
            Session("dtMultiple") = dtMultiple
        End If
        table1.Visible = False
        createvatdynamictable()

    End Sub
    'this function is used to bind the data in UserShopCart table

    Public Sub getShoppingCart(ByVal intUID As Int32, ByVal strType As String)
        If Not ds.Tables("UserShopCart") Is Nothing Then
            ds.Tables("UserShopCart").Clear()
        End If
        Dim sqlcon As New SqlConnection(ConfigurationManager.AppSettings("ConnectionString"))
        Dim cmd As New SqlCommand
        cmd.Connection = sqlcon
        cmd.CommandText = "getShopCart"
        cmd.CommandType = CommandType.StoredProcedure
        cmd.Parameters.AddWithValue("@ShopCart_BuyerUserId", intUID)  ' Select data from shop Cart according to buyeruserid
        sqlcon.Open()
        cmd.ExecuteNonQuery()
        sqlcon.Close()
        Dim da As New SqlDataAdapter
        da = New SqlDataAdapter(cmd)
        da.Fill(ds, "UserShopCart")
        dgBill.DataSource = ds.Tables("UserShop")       ' bind dgbill gridview 
    End Sub
    ' function to bind the billing addres or shipping address to lblAddress
    Private Sub getAddress(ByVal intID As String)
        If intID = "1" Then
            'lblAddress.Text = "<b>Billing Address :</b> " & "<br>" & objPL.getAdd(Session("BuyId"), intID)
            'lblAddress.Text = "<b>Billing Address :</b> " & "<br>" & GetAdd1(Session("BuyId"), intID)
            lblAddress.Text = GetAdd1(Session("BuyId"), intID)
        Else
            'lblAddress.Text = "<b>Shipment Address :</b> " & "<br>" & objPL.getAdd(Session("BuyId"), intID)
            lblAddress.Text = GetAdd2(Session("BuyId"), intID)
        End If
        
    End Sub
    ' Use String to bind the address from address book according to 

    Private Function GetAdd1(ByVal strId As String, ByVal StrAddrid As String) As String
        Dim cmd As New SqlCommand
        Dim dr As SqlDataReader
        con.Open()
        cmd = New SqlClient.SqlCommand("AddressBook_Proc", con)
        cmd.CommandType = CommandType.StoredProcedure
        cmd.Parameters.AddWithValue("@uid", strId.Trim)
        cmd.Parameters.AddWithValue("@addid", StrAddrid.Trim)
        cmd.Parameters.AddWithValue("@SCriteria", "P")
        dr = cmd.ExecuteReader()
        If dr.Read = True Then
            'Dim strAdd As New StringBuilder()
            Dim strAdd As String
            strAdd = ("<table cellspacing='0' cellpadding='0' border='0'><tr><td style='text-align: right;'><b>Billing Address :</b></td><td>" & dr.Item("AddressBook_UserName").ToString & "," & "</td></tr><tr><td></td><td>" & dr.Item("AddressBook_Add1").ToString & "," & "</td></tr><tr><td></td><td>" & dr.Item("City_Name").ToString & " " & "-" & " " & "  " & dr.Item("AddressBook_Zipcode") & "</td></tr><tr><td></td><td>" & dr.Item("State_Name") & "</td></tr><tr><td></td><td>" & dr.Item("Country_Name") & "</td></tr><tr><td style='text-align: right;'>TelePhone No :</td><td>" & dr.Item("AddressBook_TelNumber") & "</td></tr><tr><td style='text-align: right;'>Mobile No :</td><td>" & dr.Item("AddressBook_MobNumber") & "</td></tr><tr><td style='text-align: right;'><b>Email ID :</b></td><td>" & "<a href=mailto:" & dr.Item("AddressBook_Email") & " > " & dr.Item("AddressBook_Email") & "</a>" & "</td></tr></table>")
            Session("statename") = Nothing
            Session("statename") = dr.Item("State_Name")        ' this session is used in functionbindtaxvat for singleshipping
            'strAdd.Append(dr.Item("AddressBook_UserName").ToString & "," & " " & "<br>")
            'strAdd.Append(dr.Item("AddressBook_Add1").ToString & "," & " " & "<br>")
            'strAdd.Append(dr.Item("City_Name").ToString & " " & "-" & " ")
            'strAdd.Append(dr.Item("AddressBook_Zipcode") & "<br>")
            
            'strAdd.Append(dr.Item("State_Name") & "<br>" & dr.Item("Country_Name") & "<br>")
            'strAdd.Append("TelePhone No : " & dr.Item("AddressBook_TelNumber") & "<br>")
            'strAdd.Append("Mobile No :" & dr.Item("AddressBook_MobNumber") & "<br>")
            'strAdd.Append("<b>Email ID: " & "</b> ")
            'strAdd.Append("<a href=mailto:" & dr.Item("AddressBook_Email") & " > " & dr.Item("AddressBook_Email") & "</a>")
            ViewState.Add("BillingStateId", dr.Item("AddressBook_StateId"))
            ViewState.Add("BillingCityId", dr.Item("AddressBook_CityId"))
            strAdd.ToString()
            Con.Close()
            Return strAdd.ToString()
            strAdd = Nothing
        Else
            con.Close()
            Return ""
        End If
        con.Close()
    End Function
    Private Function GetAdd2(ByVal strId As String, ByVal StrAddrid As String) As String
        Dim cmd As New SqlCommand
        Dim dr As SqlDataReader
        Con.Open()
        cmd = New SqlClient.SqlCommand("AddressBook_Proc", Con)
        cmd.CommandType = CommandType.StoredProcedure
        cmd.Parameters.AddWithValue("@uid", strId.Trim)
        cmd.Parameters.AddWithValue("@addid", StrAddrid.Trim)
        cmd.Parameters.AddWithValue("@SCriteria", "P")
        dr = cmd.ExecuteReader()
        If dr.Read = True Then
            'Dim strAdd As New StringBuilder()
            Dim strAdd As String
            strAdd = ("<table cellspacing='0' cellpadding='0' border='0'><tr><td style='text-align: right;'><b>Shipment Address :</b></td><td>" & dr.Item("AddressBook_UserName").ToString & "," & "</td></tr><tr><td></td><td>" & dr.Item("AddressBook_Add1").ToString & "," & "</td></tr><tr><td></td><td>" & dr.Item("City_Name").ToString & " " & "-" & " " & "  " & dr.Item("AddressBook_Zipcode") & "</td></tr><tr><td></td><td>" & dr.Item("State_Name") & "</td></tr><tr><td></td><td>" & dr.Item("Country_Name") & "</td></tr><tr><td style='text-align: right;'>TelePhone No :</td><td>" & dr.Item("AddressBook_TelNumber") & "</td></tr><tr><td style='text-align: right;'>Mobile No :</td><td>" & dr.Item("AddressBook_MobNumber") & "</td></tr><tr><td style='text-align: right;'><b>Email ID :</b></td><td>" & "<a href=mailto:" & dr.Item("AddressBook_Email") & " > " & dr.Item("AddressBook_Email") & "</a>" & "</td></tr></table>")
            Session("statename") = Nothing
            Session("statename") = dr.Item("State_Name")        ' this session is used in functionbindtaxvat for singleshipping
            'strAdd.Append(dr.Item("AddressBook_UserName").ToString & "," & " " & "<br>")
            'strAdd.Append(dr.Item("AddressBook_Add1").ToString & "," & " " & "<br>")
            'strAdd.Append(dr.Item("City_Name").ToString & " " & "-" & " ")
            'strAdd.Append(dr.Item("AddressBook_Zipcode") & "<br>")

            'strAdd.Append(dr.Item("State_Name") & "<br>" & dr.Item("Country_Name") & "<br>")
            'strAdd.Append("TelePhone No : " & dr.Item("AddressBook_TelNumber") & "<br>")
            'strAdd.Append("Mobile No :" & dr.Item("AddressBook_MobNumber") & "<br>")
            'strAdd.Append("<b>Email ID: " & "</b> ")
            'strAdd.Append("<a href=mailto:" & dr.Item("AddressBook_Email") & " > " & dr.Item("AddressBook_Email") & "</a>")
            ViewState.Add("BillingStateId", dr.Item("AddressBook_StateId"))
            ViewState.Add("BillingCityId", dr.Item("AddressBook_CityId"))
            strAdd.ToString()
            Con.Close()
            Return strAdd.ToString()
            strAdd = Nothing
        Else
            Con.Close()
            Return ""
        End If
        Con.Close()
    End Function

    ' Function to check the order quantity

    Private Sub checkOrderQty(ByVal dt As DataTable)
        'If (dt.Rows.Count > 1 Or dt.Rows.Count = 1) And dt.Compute("sum(Product_AtcoPrice)", "Product_SellQty > 0") > 1 Then
        ShowControls(1)     ' function to show or hide the control
        'Else
        'ShowControls(2)
        'End If
    End Sub

    'code for  click event for the button of single Shipping, Multiship, Shiptoabove addres ,
    'Ship to diffrent address ,Proceed to payment.
    Public Sub add(ByVal obj As Object, ByVal e As System.EventArgs)
        If obj.ID = "btnSingle" Then
            ViewState.Add("TOS", "S")   'to check for single shipping
            ShowControls(0)
        ElseIf obj.ID = "btnSameAdd" Then
            'viewstate.Add("BE", ddBillExemp.SelectedItem.Value.Trim)
            rowTax.Visible = True
            'rowOctroi.Visible = True
            ViewState.Add("TOS", "S")   ' to check for single shipping
            'calculate tax-octroi
            functionbindtaxvat()    ' to fill the tax and vat to grid view.
            DisplayTaxOctroi(dgBill, GvTax, GvOctroi, ViewState.Item("BillingStateId"), ViewState.Item("BillingCityId"), Session("BuyId"), ViewState.Item("TOS"))
            ShowControls(3)
            lblAddress.Visible = True
        ElseIf obj.ID = "btnDiffAdd" Then
            Label4.Visible = True
            hypupdate.Visible = True
            addr.Visible = True
            'viewstate.Add("BE", ddBillExemp.SelectedItem.Value.Trim)
            objPL.getcmbData(Session("BuyID"), ddShipName)
            ddShipName.SelectedIndex = 0
            ViewState.Add("TOS", "S")    ' to check for single shipping
            'DisplayTaxOctroi(dgBill, GvTax, GvOctroi, ViewState.Item("BillingStateId"), ViewState.Item("BillingCityId"), Session("BuyId"), ViewState.Item("TOS"))

            'calculate tax-octroi
            ShowControls(4)
            lblAddress.Visible = False
            getAddress(ddShipName.SelectedItem.Value) ' function to get address of user

        ElseIf obj.ID = "btnMultiple" Then
            'objPL.chkQty(dgBill, ds.Tables("UserShopCart"), ddBillExemp, Session("DBUserID"))
            ViewState.Add("TOS", "M")
            'rowTable1.Visible = True
            vattable.Rows.Clear() 'clear row for vat table
            dt = dtProdTable()              ' table which store the item list
            Dim gvrow As GridViewRow
            For Each gvrow In dgBill.Rows
                drow = prodtable.NewRow
                drow("ProductName") = gvrow.Cells(2).Text
                Dim l5 As Label = CType(gvrow.FindControl("Label1"), Label)
                Dim l7 As Label = CType(gvrow.FindControl("lblproductid"), Label)
                Dim l8 As Label = CType(gvrow.FindControl("lblnetamount"), Label)
                drow("ProductId") = l7.Text
                drow("Quantity") = l5.Text
                drow("NetPrice") = l8.Text
                drow("SupplierId") = gvrow.Cells(6).Text
                drow("SpecialPrice") = gvrow.Cells(3).Text
                prodtable.Rows.Add(drow)
             Next
            DropDownList1.Items.Clear()
            DropDownList1.DataSource = dt
            DropDownList1.DataTextField = dt.Columns("ProductName").ToString
            DropDownList1.DataValueField = dt.Columns("ProductId").ToString
            DropDownList1.DataBind()
            Session("ProductTable") = dt
            selectAnotherAddress()          ' function to select the address of another user for shipping
            lblchk.Visible = False

            btnSingle.Visible = False
            btnMultiple.Visible = False
            btnPayment.Visible = True

            'If ViewState.Item("TOS") = "M" Then
            table1.Visible = True
            objPL.getcmbData(Session("BuyId"), ddShipName)
            Label4.Visible = True
            ddShipName.Visible = True
            hypNewAdd.Visible = True
            hypupdate.Visible = True
            addr.Visible = True
            GvLocation.Visible = False
            lblAddress.Visible = False
            'getAddress(ddShipName.SelectedItem.Value)
            'End If
        ElseIf obj.ID = "btnPayment" Then
            If ViewState.Item("TOS") = "M" Then      ' to check for multiple shipping
                If ddShipName.Visible = True And ddShipName.SelectedIndex = 0 Then
                    lblerror.Visible = True
                    lblerror.Text = "Please Select Address !! "     ' show information message
                    table1.Visible = True
                    Exit Sub
                End If
                If DropDownList1.Items.Count > 0 Then
                    lblerror.Visible = True
                    lblerror.Text = "You Have Item(s) In Shopcart, Please Ship To Address !! "  ' show information message
                    table1.Visible = True
                    Exit Sub
                End If

            End If
            If ViewState.Item("TOS") = "S" Then  ' to check for single shipping

                If ddShipName.Visible = True And ddShipName.SelectedIndex = 0 Then
                    lblerror.Visible = True
                    lblerror.Text = "Please Select Address For Shipping !! "
                    hypNewAdd.Visible = True
                    Exit Sub
                End If
            End If
            getdetails()
        End If

    End Sub

  

    Private Sub selectAnotherAddress()  ' function to select the address of another user for shipping
        ' rowLocation.Visible = True
        lblAddress.Visible = False
        GvLocation.Columns(11).Visible = True
        GvLocation.Columns(10).Visible = True
        GvLocation.Columns(9).Visible = True
        GvLocation.Columns(8).Visible = True
        GvLocation.Columns(12).Visible = False
        Dim strQuery As String = "SELECT dbo.AddressMaster.City_Kid, dbo.AddressMaster.City_Name, dbo.AddressMaster.State_Name, dbo.AddressBook.AddressBook_UserName, " & _
                                   "dbo.AddressBook.AddressBook_Zipcode, dbo.AddressMaster.Country_Name, dbo.AddressBook.AddressBook_Add1, dbo.AddressBook.AddressBook_Kid, dbo.AddressBook.AddressBook_CityID, " & _
                         "dbo.AddressBook.AddressBook_StateID,dbo.AddressBook.AddressBook_Email,dbo.AddressBook.AddressBook_CountryID " & _
                          "FROM dbo.AddressBook INNER JOIN " & _
                          "dbo.AddressMaster ON dbo.AddressBook.AddressBook_CityID = dbo.AddressMaster.City_Kid " & _
                          "where dbo.AddressBook.AddressBook_BuyerID='" & Session("BuyId") & "'"

        'query = "select * from AddressBook where AddressBook_BuyerID='" & Session("BuyId") & "'"
        GvLocation.DataSource = ReturnDataTable(strQuery)
        GvLocation.Visible = True
        GvLocation.DataBind()                   ' bind the gvlocation grid view
        GvLocation.Columns(11).Visible = False
        GvLocation.Columns(10).Visible = False
        GvLocation.Columns(9).Visible = False
        GvLocation.Columns(8).Visible = False
        GvLocation.Columns(12).Visible = False
        ' rowTable1.Visible = False
    End Sub
    ' function to display the tax and octroi for the single shippping 

    Public Sub DisplayTaxOctroi(ByVal dgbill As GridView, ByVal GvTax As GridView, ByVal GvOctroi As GridView, ByVal StateId As String, ByVal CityId As String, ByVal BuyerId As String, ByVal TOS As String)

        'Build query for octroi or tax
        Dim row As GridViewRow
        Dim TaxQuery As String = "SELECT  dbo.TaxMaster.Tax_Kid, dbo.TaxMaster.Tax_Name,dbo.TaxMaster.Tax_Form,dbo.TaxMaster.Tax_Value,dbo.TaxMaster.Tax_Deduction,dbo.TaxMaster.Tax_Type,dbo.TaxMaster.Tax_ProductId,dbo.ShopCart.ShopCart_ProductId,dbo.ShopCart.ShopCart_Quantity,dbo.ShopCart.ShopCart_NetAmount, dbo.Product_Master.Product_Name " & _
                                 "FROM dbo.TaxMaster INNER JOIN " & _
                                  "dbo.ShopCart ON dbo.TaxMaster.Tax_ProductId = dbo.ShopCart.ShopCart_ProductId INNER JOIN " & _
                                  "dbo.Product_Master ON dbo.ShopCart.ShopCart_ProductId = dbo.Product_Master.Product_Kid " & _
                                  "where dbo.ShopCart.ShopCart_BuyerUserId='" & BuyerId & "' and TaxMaster.Tax_StateId='" & StateId & "' and TaxMaster.Tax_ProductID in ("

        ' loop for each item present in the shop cart list (dgbill gridview)
        For Each row In dgbill.Rows
            Dim lb As Label = CType(row.FindControl("lblproductid"), Label) ' find the product id from dgbill gridview 
            TaxQuery = TaxQuery & "'" & lb.Text.Trim & "'" & ","
        Next
        TaxQuery = TaxQuery.Substring(0, TaxQuery.Length - 1)
        TaxQuery = TaxQuery & ")"
        dtTemp = getTable(TaxQuery, "Tax")

        'Add Tax Amount Column
        dc = New DataColumn
        dc.ColumnName = "TaxAmount"
        dtTemp.Columns.Add(dc)

        'Add Tax Amount Column with deduction
        dc = New DataColumn
        dc.ColumnName = "Taxdeduction"
        dtTemp.Columns.Add(dc)
        'Enter Tax or Octroi Amount based on Tax Type whether it is Flat or Percentage

        For Each drow In dtTemp.Rows
            If drow.Item("Tax_Type") = "P" Then
                drow.Item("TaxAmount") = drow.Item("Tax_Value") * drow.Item("ShopCart_NetAmount") * 0.01
                drow.Item("Taxdeduction") = drow.Item("Tax_Deduction") * drow.Item("ShopCart_NetAmount") * 0.01
            ElseIf drow.Item("Tax_Type") = "F" Then
                drow.Item("TaxAmount") = (drow.Item("ShopCart_Quantity") * drow.Item("Tax_Value")) + drow.Item("ShopCart_NetAmount")
                drow.Item("Taxdeduction") = (drow.Item("ShopCart_Quantity") * drow.Item("Tax_Deduction")) + drow.Item("ShopCart_NetAmount")
            End If
        Next

        'Add TaxAmount Field column dynamically in gridview
        dcbound = New BoundField
        dcbound.HeaderText = "Tax-Amount"
        dcbound.DataField = dtTemp.Columns("TaxAmount").ToString
        dcbound.DataFormatString = "{0:N2}"
        GvTax.Columns.Add(dcbound)
        'Add TaxDeduction Amount dynamically in gridview
        dcbound = New BoundField
        dcbound.HeaderText = "Tax-Deduction"
        dcbound.DataField = dtTemp.Columns("Taxdeduction").ToString
        dcbound.DataFormatString = "{0:N2}"
        GvTax.Columns.Add(dcbound)

        'Bind dttemp to GridView
        GvTax.DataSource = dtTemp
        GvTax.DataBind()
        GvTax.Columns(1).Visible = False
        GvTax.Columns(8).Visible = False
        GvTax.Columns(2).Visible = False
        GvTax.Columns(6).Visible = False
        GvTax.Columns(7).Visible = False
        If TOS = "S" Then
            ' GetOctroi(dgbill, GvTax, GvOctroi, StateId, CityId, BuyerId)
        Else
            Exit Sub
        End If

    End Sub
    ' function to display the tax and octroi for the multiship shippping

    Public Sub MDisplayTaxOctroi(ByVal GvMultipleShip As GridView, ByVal GvTax As GridView, ByVal GvOctroi As GridView, ByVal StateId As String, ByVal CityId As String, ByVal BuyerId As String, ByVal TOS As String)

        'Build query for octroi or tax
        Dim row As GridViewRow
        Dim TaxQuery As String = "SELECT  dbo.TaxMaster.Tax_Kid, dbo.TaxMaster.Tax_Name,dbo.TaxMaster.Tax_Form,dbo.TaxMaster.Tax_Value,dbo.TaxMaster.Tax_Deduction,dbo.TaxMaster.Tax_Type,dbo.TaxMaster.Tax_ProductId,dbo.ShopCart.ShopCart_ProductId,dbo.ShopCart.ShopCart_Quantity,dbo.ShopCart.ShopCart_NetAmount, dbo.Product_Master.Product_Name " & _
                                 "FROM dbo.TaxMaster INNER JOIN " & _
                                  "dbo.ShopCart ON dbo.TaxMaster.Tax_ProductId = dbo.ShopCart.ShopCart_ProductId INNER JOIN " & _
                                  "dbo.Product_Master ON dbo.ShopCart.ShopCart_ProductId = dbo.Product_Master.Product_Kid " & _
                                  "where dbo.ShopCart.ShopCart_BuyerUserId='" & BuyerId & "' and  TaxMaster.Tax_Kid in ("

        ' loop for each item present in the shop cart list (dgbill gridview)
        For Each row In GvMultipleShip.Rows
            Dim dlb As DropDownList = CType(row.FindControl("drpselectexemp"), DropDownList) ' find the product id from the dropdownbox 
            TaxQuery = TaxQuery & "'" & dlb.Text.Trim & "'" & ","
        Next
        TaxQuery = TaxQuery.Substring(0, TaxQuery.Length - 1)
        TaxQuery = TaxQuery & ")"
        dtTemp = getTable(TaxQuery, "Tax")

        'Add Tax Amount Column
        dc = New DataColumn
        dc.ColumnName = "TaxAmount"
        dtTemp.Columns.Add(dc)

        'Add Tax Amount Column with deduction
        dc = New DataColumn
        dc.ColumnName = "Taxdeduction"
        dtTemp.Columns.Add(dc)
        'Enter Tax or Octroi Amount based on Tax Type whether it is Flat or Percentage

        For Each drow In dtTemp.Rows
            If drow.Item("Tax_Type") = "P" Then
                drow.Item("TaxAmount") = drow.Item("Tax_Value") * drow.Item("ShopCart_NetAmount") * 0.01
                drow.Item("Taxdeduction") = drow.Item("Tax_Deduction") * drow.Item("ShopCart_NetAmount") * 0.01
            ElseIf drow.Item("Tax_Type") = "F" Then
                drow.Item("TaxAmount") = (drow.Item("ShopCart_Quantity") * drow.Item("Tax_Value")) + drow.Item("ShopCart_NetAmount")
                drow.Item("Taxdeduction") = (drow.Item("ShopCart_Quantity") * drow.Item("Tax_Deduction")) + drow.Item("ShopCart_NetAmount")
            End If
        Next

        'Add TaxAmount Field column dynamically in gridview
        dcbound = New BoundField
        dcbound.HeaderText = "Tax-Amount"
        dcbound.DataField = dtTemp.Columns("TaxAmount").ToString
        dcbound.DataFormatString = "{0:N2}"
        GvTax.Columns.Add(dcbound)
        'Add TaxDeduction Amount dynamically in gridview
        dcbound = New BoundField
        dcbound.HeaderText = "Tax-Deduction"
        dcbound.DataField = dtTemp.Columns("Taxdeduction").ToString
        dcbound.DataFormatString = "{0:N2}"
        GvTax.Columns.Add(dcbound)

        'Bind dttemp to GridView
        GvTax.DataSource = dtTemp
        GvTax.DataBind()
        GvTax.Columns(1).Visible = False
        GvTax.Columns(8).Visible = False
        GvTax.Columns(2).Visible = False
        GvTax.Columns(6).Visible = False
        GvTax.Columns(7).Visible = False
        GvTax.Visible = True
        If TOS = "S" Then
            ' GetOctroi(dgbill, GvTax, GvOctroi, StateId, CityId, BuyerId)
        Else
            Exit Sub
        End If

    End Sub


    Private Sub GetOctroi(ByVal dgbill As GridView, ByVal GvTax As GridView, ByVal GvOctroi As GridView, ByVal StateId As String, ByVal CityId As String, ByVal BuyerId As String)
        Dim row As GridViewRow
        Dim octroiQuery As String = "SELECT dbo.ShopCart.ShopCart_ProductId,dbo.ShopCart.ShopCart_Quantity,dbo.ShopCart.ShopCart_NetAmount, dbo.Product_Master.Product_Name, dbo.OctroiMaster.* " & _
                                           "FROM dbo.ShopCart INNER JOIN " & _
                                           "dbo.OctroiMaster ON dbo.ShopCart.ShopCart_ProductId = dbo.OctroiMaster.Octroi_ProductId INNER JOIN " & _
                                           "dbo.Product_Master ON dbo.ShopCart.ShopCart_ProductId = dbo.Product_Master.Product_Kid " & _
                                           "where dbo.ShopCart.ShopCart_BuyerUserId='" & BuyerId & "' and OctroiMaster.Octroi_CityId='" & CityId & "' and OctroiMaster.Octroi_ProductId in ("

        For Each row In dgbill.Rows
            Dim lb As Label = CType(row.FindControl("lblproductid"), Label)
            Dim ProductId As String = lb.Text.Trim()
            octroiQuery = octroiQuery & "'" & ProductId & "'" & ","
        Next

        octroiQuery = octroiQuery.Substring(0, octroiQuery.Length - 1)
        octroiQuery = octroiQuery & ")"

        dtTemp = New DataTable
        dtTemp = getTable(octroiQuery, "Octroi")
        'Add 2 columns dynamically
        dc = New DataColumn
        dc.ColumnName = "OctroiAmount"
        dtTemp.Columns.Add(dc)
        dc = New DataColumn
        dc.ColumnName = "OctroiDeductionAmt"
        dtTemp.Columns.Add(dc)
        For Each drow In dtTemp.Rows
            If drow.Item("Octroi_Type") = "P" Then
                drow.Item("OctroiAmount") = drow.Item("Octroi_Value") * drow.Item("ShopCart_NetAmount") * 0.01
                drow.Item("OctroiDeductionAmt") = drow.Item("Octroi_Deduction") * drow.Item("ShopCart_NetAmount") * 0.01
            ElseIf drow.Item("Octroi_Type") = "F" Then
                drow.Item("OctroiAmount") = (drow.Item("ShopCart_Quantity") * drow.Item("Octroi_Value")) + drow.Item("ShopCart_NetAmount")
                drow.Item("OctroiDeductionAmt") = (drow.Item("ShopCart_Quantity") * drow.Item("Octroi_Deduction")) + drow.Item("ShopCart_NetAmount")
            End If
        Next
        dcbound = New BoundField
        dcbound.HeaderText = "Octroi-Amount"
        dcbound.DataField = dtTemp.Columns("OctroiAmount").ToString
        dcbound.DataFormatString = "{0:N2}"
        GvOctroi.Columns.Add(dcbound)

        dcbound = New BoundField
        dcbound.HeaderText = "Octroi-deductionAmt"
        dcbound.DataField = dtTemp.Columns("OctroiDeductionAmt").ToString
        dcbound.DataFormatString = "{0:N2}"
        GvOctroi.Columns.Add(dcbound)

        GvOctroi.DataSource = dtTemp
        GvOctroi.DataBind()
        GvOctroi.Columns(1).Visible = False
        GvOctroi.Columns(3).Visible = False
        GvOctroi.Columns(7).Visible = False
        GvOctroi.Columns(2).Visible = False
        GvOctroi.Columns(5).Visible = False
        GvOctroi.Columns(6).Visible = False
        GvOctroi.Visible = False
    End Sub

    ' function to get the details  called from payment to proceed button

    Private Sub getdetails()
        Dim intAmt As Int32
        If viewstate.Item("TOS") = "S" Then
            If viewstate.Item("DA") Is Nothing And ddShipName.Visible = False Then
                'viewstate.Add("SE", ddBillExemp.SelectedItem.Value.Trim)
                'intAmt = objPL.UpdateData(Session("DBUserID"), "S", 1, viewstate.Item("BE"), viewstate.Item("SE"))
                DisplayTaxOctroi(dgBill, GvTax, GvOctroi, ViewState.Item("BillingStateId"), ViewState.Item("BillingCityId"), Session("BuyId"), "S")

                intAmt = objPL.UpdateData(Session("BuyID"), "S", 1, dgBill, gvvat, GvTax, GvOctroi)
                viewstate.Clear()
                'Server.Transfer("PaymentDetails.aspx?Amt=" & intAmt & "")


            Else
                If ddShipName.Visible = True And viewstate.Item("DA") Is Nothing Then
                    viewstate.Add("DA", ddShipName.SelectedItem.Value)
                    ShowControls(5)
                    DisplayTaxOctroi(dgBill, GvTax, GvOctroi, ViewState.Item("BillingStateId"), ViewState.Item("BillingCityId"), Session("BuyId"), "S")
                    intAmt = objPL.UpdateData(Session("BuyID"), "S", ViewState.Item("DA"), dgBill, gvvat, GvTax, GvOctroi)

                Else

                    DisplayTaxOctroi(dgBill, GvTax, GvOctroi, ViewState.Item("BillingStateId"), ViewState.Item("BillingCityId"), Session("BuyId"), "DA")
                    ' this function is called in billingpl.vb file
                    intAmt = objPL.UpdateData(Session("BuyID"), "S", ViewState.Item("DA"), dgBill, gvvat, GvTax, GvOctroi)
                    ViewState.Clear()
                    'Server.Transfer("PaymentDetails.aspx?Amt=" & intAmt & "")

                End If
               
            End If
            Session("singleship") = lblAddress.Text  ' Session for paymentDeatils.aspx form for user address
            Response.Redirect("PaymentDetails.aspx?Amt=" & intAmt & "")

        ElseIf viewstate.Item("TOS") = "M" Then
               MDisplayTaxOctroi(GvMultipleShip, GvTax, GvOctroi, ViewState.Item("BillingStateId"), ViewState.Item("BillingCityId"), Session("BuyId"), "M")
            intAmt = objPL.Updata(Session("BuyId"), ViewState.Item("TOS"), GvMultipleShip, gvvat, GvTax, GvOctroi, Me.Page)
            GvOctroi.Columns(1).Visible = False
            GvOctroi.Columns(2).Visible = False
            Response.Redirect("PaymentDetails.aspx?Amt=" & intAmt & "")
        End If
    End Sub


    '*************************************************************************
    Public Function UpData(ByVal intUserId As String, ByVal strTos As String, ByVal GvMultipleShip As GridView, ByVal GvTax As GridView, ByVal GvOctroi As GridView) As Decimal
        'Return CalTax1(intUserId, strTos.Trim, dgBill, GvTax, GvOctroi, GvMultipleShip)
        getBillingTable()
        Dim i As Integer = 0
    End Function

    Private Sub GetBillNo(ByVal Inv As String)

    End Sub
    ' function to fetch data form billheader , billdetails and billingaddress

    Protected Sub getBillingTable()
        Dim daHeader As SqlDataAdapter
        Dim daDetails As SqlDataAdapter
        Dim daAddress As SqlDataAdapter
        Dim strBNo As String = "@#$@#$@#$@#$"
        If con.State = ConnectionState.Open Then
            con.Close()
        End If
        If Not ds.Tables("Header") Is Nothing Then          ' ds for billing header
            ds.Tables("Header").Clear()
        End If
        sql = "Select * from BillingHeader where BillingHeader_BillNo='" & strBNo.Trim & "'"
        daHeader = New SqlClient.SqlDataAdapter(sql, con)
        daHeader.Fill(ds, "Header")
        If Not ds.Tables("BD") Is Nothing Then
            ds.Tables("BD").Clear()
        End If
        sql = "Select * from BillDetails where BillDetails_BillNo='" & strBNo.Trim & "'"
        daDetails = New SqlClient.SqlDataAdapter(sql, con)
        daDetails.Fill(ds, "BD")                                   'ds for billing details     
        If Not ds.Tables("Address") Is Nothing Then
            ds.Tables("Address").Clear()
        End If
        sql = "Select * from BillingAddress where BillingAddress_BillNo='" & strBNo.Trim & "'"
        daAddress = New SqlClient.SqlDataAdapter(sql, con)
        daAddress.Fill(ds, "Address")                               ' ds for billingAddress
    End Sub

    ''******************** Changes the Visibility of Controls according to action ****************************
    Private Sub ShowControls(ByVal intvalue As Int32)
        If intvalue = 1 Then
            btnMultiple.Visible = True
            btnSingle.Visible = True
            lblchk.Visible = True

        ElseIf intvalue = 2 Then
            lblAddress.Visible = True
            btnSameAdd.Visible = True
            btnDiffAdd.Visible = True
            'ddBillExemp.Visible = True
            'lblSelectExemp.Visible = True
        ElseIf intvalue = 0 Then
            btnMultiple.Visible = False
            btnSingle.Visible = False
            lblchk.Visible = False

            lblAddress.Visible = True
            btnSameAdd.Visible = True
            btnDiffAdd.Visible = True
            'ddBillExemp.Visible = True
            'lblSelectExemp.Visible = True
        ElseIf intvalue = 3 Then
            lblAddress.Visible = False
            btnDiffAdd.Visible = False
            btnSameAdd.Visible = False
            btnPayment.Visible = True
            'lblSelectExemp.Visible = True
            'lblSelectExemp.Text = "Select Shipment Exemption : "
        ElseIf intvalue = 4 Then
            lblAddress.Visible = False
            btnSameAdd.Visible = False
            btnDiffAdd.Visible = False
            'lblSelectExemp.Visible = False
            'ddBillExemp.Visible = False
            ddShipName.Visible = True
            'btnSameAdd.Visible = True
            btnPayment.Visible = True
            hypNewAdd.Visible = True
        ElseIf intvalue = 5 Then
            hypNewAdd.Visible = False
            ddShipName.Visible = False
            lblAddress.Visible = True
            getAddress(ddShipName.SelectedItem.Value)
            'lblSelectExemp.Visible = True
            'ddBillExemp.Visible = True
        ElseIf intvalue = 6 Then
            lblchk.Visible = False

            btnMultiple.Visible = False
            btnSingle.Visible = False
            lblAddress.Visible = True
            getAddress(1)
            'lblSelectExemp.Visible = True
            'ddBillExemp.Visible = True
            btnPayment.Visible = True
        End If
    End Sub


    'To bind dropdownlist to no of products in a shopping cart
    Public Function dtProdTable() As DataTable
        prodtable.Rows.Clear()
        prodtable.Columns.Clear()
        With prodtable.Columns
            .Add("ProductName", GetType(System.String))
            .Add("ProductId", GetType(System.String))
            .Add("Quantity", GetType(System.String))
            .Add("NetPrice", GetType(System.Decimal))
            .Add("SupplierId", GetType(System.String))
            .Add("SpecialPrice", GetType(System.Decimal))
            .Add("CityId", GetType(System.String))
        End With
        Return prodtable
    End Function

    ' to add the one more item to particular address for shipping
    Protected Sub BtnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnAdd.Click
        DropDownList1.SelectedIndex = 0
        lblerror.Visible = False
        If ddShipName.SelectedIndex = 0 Then

            lblerror.Visible = True
            lblerror.Text = "Please Select Address !!"
            table1.Visible = True
        Else
            If CheckValidation() = True Then
                GvMultipleShip.Visible = True
                FormTable(CInt(txtQuantity.Text.Trim)) ' function  to bind gvmultiship gridview
                GvMultipleShip.Visible = False
            Else
                Exit Sub
            End If

            objPL.getcmbData(Session("BuyId"), ddShipName) 'Get the Data for Changing the  shipping Address for Single shipping in combobox and called in billingmoule.vb file
            Label4.Text = "Select Next Address"
            Label4.Visible = True
            lblAddress.Visible = False
            table1.Visible = True                       ' table for add more product 
            If DropDownList1.Items.Count < 1 Then
                table1.Visible = False
                ddShipName.Visible = False
                Label4.Text = "Congratulation You Can Proceed To Payment!!"
                GvMultipleShip.Visible = False
                dgBill.Visible = False
                hypNewAdd.Visible = False
                hypupdate.Visible = False
                addr.Visible = False
            End If

        End If
    End Sub
    'function to hide or visible the control for multiship

    Function Multicheck()
        GvLocation.Visible = False
        ddShipName.Visible = True
        hypNewAdd.Visible = True
        hypupdate.Visible = True
        addr.Visible = True
        Label4.Visible = False
        table1.Visible = True
        lblAddress.Visible = True
        Return False

    End Function

    'Do validation against ProductId and quantity
    Protected Function CheckValidation() As Boolean
        Try
            Dim dttemp As New DataTable
            Dim MultipleShipTable As New DataTable

            dttemp = CType(Session("ProductTable"), DataTable)
            MultipleShipTable = CType(Session("dtMultiple"), DataTable)

            Dim quantity As Integer = 0
            Dim i As Integer = 0
            Dim drsearch As DataRow()
            'drsearch = prodtable.Select("ProductId='" & DropDownList1.SelectedValue & "'")
            drsearch = dttemp.Select("ProductId='" & DropDownList1.SelectedValue & "'")
            If txtQuantity.Text.Trim = "" Or Not IsNumeric(txtQuantity.Text) Then
                'CreateMessageAlert(Me.Page, "Enter the quantity", "strKey")

                lblerror.Text = "Enter the Valid quantity !!"
                lblerror.Visible = True
                Multicheck()
                Return False
                Exit Function
            End If
            If txtQuantity.Text = 0 Then
                lblerror.Text = "Enter the Valid quantity !!"
                lblerror.Visible = True
                Multicheck()
                Return False
                Exit Function
            End If

            Dim drsearch1 As DataRow()
            drsearch1 = MultipleShipTable.Select("ProductId='" & DropDownList1.SelectedValue & "'")
            If drsearch1.Length > 0 Then
                For i = 0 To drsearch1.Length - 1
                    quantity = quantity + CInt(drsearch1(i).Item("Quantity"))
                Next
            End If
            If drsearch1.Length > 0 Then
                If drsearch.Length > 0 Then
                    If CInt(txtQuantity.Text) > CInt(drsearch(0).Item("Quantity")) - quantity Then
                        'CreateMessageAlert(Me.Page, "You cannot enter more Quantity", "strKey")

                        lblerror.Text = "You cannot enter more Quantity !!"
                        lblerror.Visible = True
                        Multicheck()
                        Return False
                        Exit Function
                    End If
                End If
            End If

            If drsearch.Length > 0 Then
                If CInt(txtQuantity.Text) > CInt(drsearch(0).Item("Quantity")) Then
                    'CreateMessageAlert(Me.Page, "You cannot enter more Quantity compared to your shopping cart", "strKey")

                    lblerror.Text = "You cannot enter more Quantity compared to your shopping cart !!"
                    lblerror.Visible = True
                    Multicheck()
                    Return False
                    Exit Function
                End If
            End If



            Return True

        Catch ex As Exception

        End Try

       
    End Function

    Private Sub FormTable(ByVal ShipQuantity As Integer)
        'search for productId and ShippingId
        Try
            Dim dtProduct As New DataTable
            Dim MultipleShipTable As New DataTable
            dtProduct = CType(Session("ProductTable"), DataTable)
            MultipleShipTable = CType(Session("dtMultiple"), DataTable)
            drsearch1 = MultipleShipTable.Select("ProductId='" & DropDownList1.SelectedValue & "' and ShippingId='" & ddShipName.SelectedValue & "'")
            If drsearch1.Length > 0 Then
                Dim shippingId As String = ddShipName.SelectedValue
                Dim ProductId As String = DropDownList1.SelectedValue
                Dim drMultipleShipRow As DataRow()
                drMultipleShipRow = MultipleShipTable.Select("ProductId='" & DropDownList1.SelectedValue & "' and ShippingId='" & shippingId & "'")
                If drMultipleShipRow.Length > 0 Then
                    GvMultipleShip.Columns(1).Visible = True
                    GvMultipleShip.Columns(3).Visible = True
                    GvMultipleShip.Columns(6).Visible = True
                    GvMultipleShip.Columns(7).Visible = True
                    GvMultipleShip.Columns(8).Visible = True
                    GvMultipleShip.Columns(11).Visible = True

                    drMultipleShipRow(0).BeginEdit()
                    Dim OrderQty As String = drMultipleShipRow(0).Item(2).ToString
                    drMultipleShipRow(0).Item("Quantity") = CInt(OrderQty) + ShipQuantity
                    drsearch = dtProduct.Select("ProductId='" & DropDownList1.SelectedValue & "'")
                    If drsearch.Length > 0 Then
                        netAmount = Convert.ToDecimal(drsearch(0).Item("SpecialPrice"))
                    End If
                    drMultipleShipRow(0).Item("NetAmount") = netAmount * (CInt(OrderQty) + ShipQuantity)
                    drMultipleShipRow(0).EndEdit()
                    findcityaddress()
                    'bindtaxtable()
                    MultipleShipTable.Rows.Add(drow)
                    GvMultipleShip.DataSource = MultipleShipTable
                    GvMultipleShip.DataBind()
                    Dim i As Integer
                    i = 0
                    For i = 0 To GvMultipleShip.Rows.Count - 1
                        '                        bindtaxtable(i)
                        functionbindtaxvat(i)    ' to fill the tax and vat to grid view.
                    Next
                    GvMultipleShip.Columns(1).Visible = False
                    GvMultipleShip.Columns(3).Visible = False
                    GvMultipleShip.Columns(7).Visible = False
                    GvMultipleShip.Columns(8).Visible = False
                    GvMultipleShip.Columns(6).Visible = False
                    GvMultipleShip.Columns(11).Visible = False
                    Session("dtMultiple") = MultipleShipTable
                Else
                    GvMultipleShip.Columns(1).Visible = True
                    GvMultipleShip.Columns(3).Visible = True
                    GvMultipleShip.Columns(7).Visible = True
                    GvMultipleShip.Columns(8).Visible = True
                    GvMultipleShip.Columns(6).Visible = True
                    GvMultipleShip.Columns(11).Visible = True
                    drow = MultipleShipTable.NewRow
                    drow("ProductName") = DropDownList1.SelectedItem.Text
                    drow("ProductId") = DropDownList1.SelectedValue
                    drow("Quantity") = ShipQuantity

                    findcityaddress()
                    drow("Shipping Address") = CType(GvLocation.SelectedRow.FindControl("lblShippingAdress"), Label).Text
                    drow("ShippingId") = GvLocation.SelectedRow.Cells(11).Text
                    drsearch = dtProduct.Select("ProductId='" & drow("ProductId") & "'")
                    If drsearch.Length > 0 Then
                        netAmount = Convert.ToDecimal(drsearch(0).Item("NetPrice"))
                    End If
                    drow("Special Price") = Convert.ToDecimal(drsearch(0).Item("SpecialPrice"))
                    drow("NetAmount") = Convert.ToDecimal(drsearch(0).Item("SpecialPrice")) * ShipQuantity

                    If drsearch.Length > 0 Then
                        drow("SupplierId") = drsearch(0).Item("SupplierId")
                    End If


                    'GvMultipleShip.Columns(1).Visible = True
                    'GvMultipleShip.Columns(9).Visible = True
                    'bindtaxtable()
                    MultipleShipTable.Rows.Add(drow)
                    GvMultipleShip.DataSource = MultipleShipTable
                    GvMultipleShip.DataBind()
                    Dim i As Integer
                    i = 0
                    For i = 0 To GvMultipleShip.Rows.Count - 1
                        'bindtaxtable(i)
                        functionbindtaxvat(i)    ' to fill the tax and vat to grid view.
                    Next
                    GvMultipleShip.Columns(1).Visible = False
                    GvMultipleShip.Columns(3).Visible = False
                    GvMultipleShip.Columns(7).Visible = False
                    GvMultipleShip.Columns(8).Visible = False
                    GvMultipleShip.Columns(6).Visible = False
                    GvMultipleShip.Columns(11).Visible = False
                    Session("dtMultiple") = MultipleShipTable
                End If
            Else
                GvMultipleShip.Columns(1).Visible = True
                GvMultipleShip.Columns(3).Visible = True
                GvMultipleShip.Columns(7).Visible = True
                GvMultipleShip.Columns(8).Visible = True
                GvMultipleShip.Columns(6).Visible = True
                GvMultipleShip.Columns(11).Visible = True
                drow = MultipleShipTable.NewRow
                drow("ProductName") = DropDownList1.SelectedItem.Text
                drow("ProductId") = DropDownList1.SelectedValue
                drow("Quantity") = ShipQuantity

                drsearch = dtProduct.Select("ProductId='" & DropDownList1.SelectedValue & "'")
                drsearch = dtProduct.Select("ProductId='" & drow("ProductId") & "'")
                drow("Special Price") = Convert.ToDecimal(drsearch(0).Item("SpecialPrice"))
                drow("NetAmount") = Convert.ToDecimal(drsearch(0).Item("SpecialPrice")) * ShipQuantity
                findcityaddress()

                drsearch = dtProduct.Select("ProductId='" & drow("ProductId") & "'")
                If drsearch.Length > 0 Then
                    netAmount = Convert.ToDecimal(drsearch(0).Item("NetPrice"))
                End If

                If drsearch.Length > 0 Then
                    drow("SupplierId") = drsearch(0).Item("SupplierId")
                End If


                'GvLocation.Visible = False

                MultipleShipTable.Rows.Add(drow)
                GvMultipleShip.DataSource = MultipleShipTable


                GvMultipleShip.DataBind()
                Session("dtMultiple") = MultipleShipTable
                GvMultipleShip.Columns(1).Visible = False
                GvMultipleShip.Columns(3).Visible = False
                GvMultipleShip.Columns(7).Visible = False
                GvMultipleShip.Columns(8).Visible = False
                GvMultipleShip.Columns(6).Visible = False
                GvMultipleShip.Columns(11).Visible = False
                Dim i As Integer
                i = 0
                For i = 0 To GvMultipleShip.Rows.Count - 1
                    'bindtaxtable(i)                         ' function to bind dynamic tax table
                    functionbindtaxvat(i)    ' to fill the tax and vat to grid view.
                Next
            End If

            drsearch1 = MultipleShipTable.Select("ProductId='" & DropDownList1.SelectedValue & "'")
            quantity = 0
            If drsearch1.Length > 0 Then
                For i = 0 To drsearch1.Length - 1
                    quantity = quantity + CInt(drsearch1(i).Item("Quantity"))
                Next
            End If

           quantity1 = CInt(drsearch(0).Item("Quantity"))
            If quantity = quantity1 Then
                dtProduct.Rows.Remove(drsearch(0))
                DropDownList1.Items.Clear()
                DropDownList1.DataSource = dtProduct
                DropDownList1.DataBind()
            End If

            If dtProduct.Rows.Count = 0 Then

                table1.Visible = False
                'Retrive the Billing Address from Buyer_Master
                Dim StateId As String = GetStateId()    ' function to get state id
                rowTax.Visible = True
                ' rowOctroi.Visible = True
                ' rowLocation.Visible = False
                ' DisplayTaxOctroi(dgBill, GvTax, GvOctroi, StateId, ViewState.Item("BillingCityId"), Session("BuyId"), ViewState.Item("TOS"))
                'DisplayTaxOctroi(dgbill, GvTax, GvOctroi, StateId, ViewState.Item("BillingCityId"), Session("BuyId"), ViewState.Item("TOS"))
                DisplayOctroi()
                btnPayment.Visible = True
                btnSingle.Visible = False
                btnMultiple.Visible = False
                'Gettax()
                'BtnTax.Visible = True

            End If
            Session("singleship") = Nothing
            'Session("Shippdetail") = MultipleShipTable  ' this session is used in paymentdetails.aspx form.
            txtQuantity.Text = ""
            'rowMultipleShip.Visible = True
          
        Catch
        End Try
    End Sub

    Protected Sub DisplayOctroi()
        Dim dcbound As BoundField
        Dim DtTemp As New DataTable
        Dim dc As DataColumn
        'sandhya
        'Add City Kid column
        With DtTemp.Columns
            .Add("Octroi_Kid", GetType(System.String))
            .Add("Octroi_ProductId", GetType(System.String))
            .Add("Product_Name", GetType(System.String))
            .Add("Octroi_Form", GetType(System.String))
            .Add("Octroi_Value", GetType(System.String))
            .Add("Octroi_Deduction", GetType(System.String))
            .Add("Octroi_Type", GetType(System.String))
            .Add("Product_Quantity", GetType(System.Int32))
            .Add("Product_SpecialPrice", GetType(System.Decimal))
            .Add("Product_NetPrice", GetType(System.Decimal))
            .Add("Product_CityId", GetType(System.String))
        End With
        Dim dr As SqlDataReader
        Dim GvRow As GridViewRow
        For Each GvRow In GvMultipleShip.Rows
            'HtMLEncode check for property 
            query = "select Octroi_Kid,Octroi_ProductId,Octroi_Value,Octroi_Form,Octroi_Deduction,Octroi_Type,Octroi_CityId from OctroiMaster where Octroi_ProductId='" & GvRow.Cells(1).Text & "' and Octroi_CityId='" & GvRow.Cells(7).Text & "'"
            Dim sqlcon As New SqlConnection(ConfigurationManager.AppSettings("ConnectionString"))
            Dim cmd As New SqlCommand(query, sqlcon)
            sqlcon.Open()
            dr = cmd.ExecuteReader
            Do While dr.Read
                drow = DtTemp.NewRow
                drow("Octroi_Kid") = RemoveLiterals(dr(0))
                drow("Octroi_ProductId") = RemoveLiterals(dr(1))
                drow("Product_Name") = GvRow.Cells(0).Text
                drow("Octroi_Form") = dr(3)
                drow("Octroi_Value") = dr(2)
                drow("Octroi_Deduction") = dr(4)
                drow("Octroi_Type") = dr(5)
                drow("Product_Quantity") = GvRow.Cells(2).Text
                drow("Product_SpecialPrice") = GvRow.Cells(5).Text
                drow("Product_NetPrice") = GvRow.Cells(6).Text
                drow("Product_CityId") = dr(6)
                DtTemp.Rows.Add(drow)
            Loop
            sqlcon.Close()
        Next
        'Add 2 columns dynamically in the table
        dc = New DataColumn
        dc.ColumnName = "OctroiAmount"
        DtTemp.Columns.Add(dc)

        dc = New DataColumn
        dc.ColumnName = "OctroiDeductionAmt"
        DtTemp.Columns.Add(dc)

        dc = New DataColumn
        dc.ColumnName = "CityId"
        DtTemp.Columns.Add(dc)

        For Each drow In DtTemp.Rows
            If drow.Item("Octroi_Type") = "P" Then
                drow.Item("OctroiAmount") = drow.Item("Octroi_Value") * drow.Item("Product_NetPrice") * 0.01
                drow.Item("OctroiDeductionAmt") = drow.Item("Octroi_Deduction") * drow.Item("Product_NetPrice") * 0.01
            ElseIf drow.Item("Octroi_Type") = "F" Then
                drow.Item("OctroiAmount") = (drow.Item("Product_Quantity") * drow.Item("Octroi_Value"))
                drow.Item("OctroiDeductionAmt") = (drow.Item("Product_Quantity") * drow.Item("Octroi_Deduction"))
            End If
        Next

        dcbound = New BoundField
        dcbound.HeaderText = "Octroi-Amount"
        dcbound.DataField = DtTemp.Columns("OctroiAmount").ToString
        dcbound.DataFormatString = "{0:N2}"
        GvOctroi.Columns.Add(dcbound)

        dcbound = New BoundField
        dcbound.HeaderText = "Octroi-deductionAmt"
        dcbound.DataField = DtTemp.Columns("OctroiDeductionAmt").ToString
        dcbound.DataFormatString = "{0:N2}"
        GvOctroi.Columns.Add(dcbound)

        dcbound = New BoundField
        dcbound.HeaderText = "CityId"
        dcbound.DataField = DtTemp.Columns("Product_CityId").ToString
        GvOctroi.Columns.Add(dcbound)

        GvOctroi.DataSource = DtTemp
        GvOctroi.DataBind()

        GvOctroi.Columns(1).Visible = True
        GvOctroi.Columns(2).Visible = True
        GvOctroi.Columns(7).Visible = True
    End Sub
    ' function to get stateid and this is called from FormTable function

    Private Function GetStateId() As String
        Dim StateId As String = ""
        Dim CityId As String = ""
        Try
            query = "select BuyerRegister_StateId,BuyerRegister_CityId from BuyerRegister where BuyerRegister_Kid='" & Session("BuyId") & "'"
            Dim SqlCon As New SqlConnection(ConfigurationManager.AppSettings("ConnectionString")) ' Declare Connection Variable
            Dim sqlCmd As New SqlCommand(query, SqlCon)  ' Declare Command Variable
            Dim dr As SqlDataReader
            SqlCon.Open()
            dr = sqlCmd.ExecuteReader
            Do While dr.Read
                StateId = dr(0)
                CityId = dr(1)
                ViewState.Item("BillingCityId") = CityId
            Loop
            SqlCon.Close()
        Catch ex As Exception
            ex.Message.ToString()
        End Try
        Return StateId
    End Function

    ' create the dynamic table.
    Protected Function dtMultipleTemp() As DataTable
        MultipleShipTable.Columns.Clear()
        With MultipleShipTable.Columns
            .Add("ProductName", GetType(System.String))
            .Add("ProductId", GetType(System.String))
            .Add("Quantity", GetType(System.String))
            .Add("Shipping Address", GetType(System.String))
            .Add("ShippingId", GetType(System.String))
            .Add("Special Price", GetType(System.Decimal))
            .Add("NetAmount", GetType(System.Decimal))
            .Add("CityId", GetType(System.String))
            .Add("stateId", GetType(System.String))
            .Add("SupplierId", GetType(System.String))
            .Add("UserName", GetType(System.String))
            .Add("StateName", GetType(System.String))
        End With
        Return MultipleShipTable
    End Function
    ' bind the total and netamount in dgbill gridview

    Protected Sub dgBill_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles dgBill.RowDataBound
        If e.Row.RowType = DataControlRowType.Footer Then
            Dim l2 As Label = CType(e.Row.Cells(5).FindControl("label2"), Label)
            l2.Text = "Total"
            Dim l1 As Label = CType(e.Row.Cells(8).FindControl("lblnetamount"), Label)
            l1.Text = FormatNumber(amount, 2)
        End If


    End Sub

    Protected Sub DropDownList1_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropDownList1.DataBound

    End Sub

    ' function to bind the country,city,state dropdown list
    Private Sub fillCombos()
        Dim strquery As String
        strquery = "SELECT DISTINCT Country_Kid, Country_Name FROM Country_Master WHERE (Country_IsDeleted = '0') order by Country_Name"
        If Not drpCountry Is Nothing Then
            Fill_Combo(strquery, drpCountry)
        End If
        drpCountry.Items.FindByText("India").Selected = True

        strquery = "SELECT DISTINCT State_Kid, State_Name FROM State_Master WHERE (State_IsDeleted = '0') order by State_Name "
        If Not drpState Is Nothing Then
            Fill_Combo(strquery, drpState)
        End If
        strquery = "SELECT DISTINCT City_Kid, City_Name FROM City_Master WHERE (City_IsDeleted = '0') order by City_Name"
        If Not drpCity Is Nothing Then
            Fill_Combo(strquery, drpCity)
        End If

    End Sub

    'code to insert the address in address book
    Protected Sub btnInsert_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnInsert.Click

        Dim UserName As String = txtusername.Text
        Dim address As String = txtaddress.Text
        Dim zipcode As String = txtZipCode.Text
        Dim Extno As String = txtextno.Text
        Dim TelNo As String = txttcode.Text & "-" & txtcitycode.Text & "-" & txtTelNo.Text
        Dim MobNo As String = txtmcode.Text & "-" & txtMobNo.Text
        Dim email As String = txtEmail.Text

        Dim country As String = drpCountry.SelectedValue
        Dim state As String = drpState.SelectedValue
        Dim city As String = drpCity.SelectedValue

        Dim addressId As String = NewPrimaryKey(Me.Page)    ' generate new address book kid

        addressId = RemoveLiterals(addressId)
        query = "insert into AddressBook(AddressBook_Kid,AddressBook_BuyerID,AddressBook_UserName,AddressBook_Add1,AddressBook_CityID,AddressBook_StateID,AddressBook_Zipcode,AddressBook_CountryID,AddressBook_TelExtn,AddressBook_TelNumber,AddressBook_MobNumber,AddressBook_Email,AddressBook_Flag,AddressBook_FinancialYearId,AddressBook_CompanyId,AddressBook_UserId) values('" & addressId & "','" & Session("BuyId") & "','" & UserName & "','" & address & "','" & city & "','" & state & "','" & zipcode & "','" & country & "','" & Extno.Trim & "','" & TelNo.Trim & "','" & MobNo.Trim & "','" & email & "','0','" & Session("g_FinYear") & "','" & Session("g_Company") & "','" & Session("UserId") & "')"

        Dim cmd As New SqlCommand
        Dim SqlCon As New SqlConnection(ConfigurationManager.AppSettings("ConnectionString"))
        cmd.CommandText = query
        cmd.Connection = SqlCon

        SqlCon.Open()
        cmd.ExecuteNonQuery()
        Session("AddressID") = addressId        ' 
        SqlCon.Close()
        cmd.Dispose()
        SqlCon.Dispose()
        objPL.getcmbData(Session("BuyId"), ddShipName)
        ddShipName.Items.FindByValue(addressId).Selected = True
        lblAddress.Visible = True
        GetAdd1(Session("BuyId"), ddShipName.SelectedValue)
        If ddShipName.SelectedIndex <> 0 Then
            lblAddress.Visible = True
        End If
        If ViewState.Item("TOS") = "M" Then
            table1.Visible = True
        End If
        ddShipName.Visible = True
        btnUpdate.Visible = False
        lblAddress.Visible = True
        getAddress(ddShipName.SelectedItem.Value) ' Use String Builder to bind the address from address book according to 

        pnladdress.Visible = False
        ddShipName.Enabled = True
        clearfields()                   ' function to clear the fields
    End Sub
    Public Sub drpCountry_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles drpCountry.SelectedIndexChanged

        Dim strquery As String = "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_IsDeleted = '0' AND Country_Master.Country_Kid = '" & drpCountry.SelectedValue & "' ORDER BY State_Master.State_Name"
        Fill_Combo(strquery, drpState)
        strquery = "select Country_ISDCode from Country_Master where Country_Kid='" & drpCountry.SelectedValue & "'"
        txttcode.Text = chkDBNull(ReturnValue(strquery))
        txtmcode.Text = txttcode.Text
    End Sub


    Public Sub drpState_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles drpState.SelectedIndexChanged

        Dim strquery As String = "SELECT 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 State_Master.State_Kid = '" & drpState.SelectedValue & "'"
        Fill_Combo(strquery, drpCity)
    End Sub
    ' code for cancel button
    Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        If ddShipName.SelectedIndex <> 0 Then
            lblAddress.Visible = True
            getAddress(ddShipName.SelectedItem.Value)
        Else
            lblAddress.Visible = False
        End If
        If ViewState.Item("TOS") = "M" Then
            table1.Visible = True
        End If
        ddShipName.Visible = True
        btnUpdate.Visible = False

        pnladdress.Visible = False
        ddShipName.Enabled = True

    End Sub

    ' code to select the address for shipping using username
    Protected Sub ddShipName_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddShipName.SelectedIndexChanged
        lblerror.Visible = False
        If ViewState.Item("TOS") = "M" Then

            Label4.Visible = False
            ddShipName.Visible = True
            hypNewAdd.Visible = True
            hypupdate.Visible = True
            addr.Visible = True
            GvLocation.Visible = False
            lblAddress.Visible = True
            table1.Visible = True
            getAddress(ddShipName.SelectedItem.Value) ' function to bind the shipping address.
            lblerror.Visible = False
        Else

            lblAddress.Visible = True
            getAddress(ddShipName.SelectedItem.Value)
            functionbindtaxvat()
        End If
        ' to fill the tax and vat to grid view.
    End Sub

    ' function to update  the fill the text field for update the address of user 
    Private Function GetUpdatedata(ByVal strId As String, ByVal StrAddrid As String) As String
        cmd = New SqlClient.SqlCommand("AddressBook_Proc", con)
        cmd.CommandType = CommandType.StoredProcedure
        cmd.Parameters.AddWithValue("@uid", strId.Trim)
        cmd.Parameters.AddWithValue("@addid", StrAddrid.Trim)
        cmd.Parameters.AddWithValue("@SCriteria", "P")
        con.Open()
        dr = cmd.ExecuteReader()
        If dr.Read = True Then

            txtusername.Text = dr.Item("AddressBook_UserName").ToString
            txtaddress.Text = dr.Item("AddressBook_Add1").ToString
            txtZipCode.Text = dr.Item("AddressBook_Zipcode")

            Dim telno As String = dr.Item("AddressBook_TelNumber")
            If telno.IndexOf("-") = -1 Then
                txtTelNo.Text = dr.Item("AddressBook_TelNumber")
            Else
                txttcode.Text = telno.Substring(0, telno.IndexOf("-"))

                telno = telno.Substring(telno.IndexOf("-") + 1)
                txtcitycode.Text = telno.Substring(0, telno.IndexOf("-"))
                telno = telno.Substring(telno.IndexOf("-") + 1)
                txtTelNo.Text = telno

            End If

            telno = dr.Item("AddressBook_MobNumber")
            If telno.IndexOf("-") = -1 Then
                txtMobNo.Text = dr.Item("AddressBook_MobNumber")
            Else
                txtmcode.Text = telno.Substring(0, telno.IndexOf("-"))
                txtMobNo.Text = telno.Substring(telno.IndexOf("-") + 1)

            End If
            'txtTelNo.Text = dr.Item("AddressBook_TelNumber")
            txtEmail.Text = dr.Item("AddressBook_Email")
            txtextno.Text = dr.Item("AddressBook_TelExtn")
            Dim kid As String = StrAddrid.Trim
            BindCountryStateCity(kid)                   ' function to fetch the country,state ,city and bind to dropdownlist
            drpCountry.Items.FindByText(dr.Item("Country_Name").ToString.Trim).Selected = True
            drpState.Items.FindByText(dr.Item("State_Name").Trim).Selected = True
            drpCity.Items.FindByText(dr.Item("City_Name").ToString.Trim).Selected = True

        End If
        con.Close()

    End Function
    ' function to fetch the country,state ,city and bind to dropdownlist
    Private Sub BindCountryStateCity(ByVal kid As String)

        Dim strquery As String
        Dim country As String = ReturnValue("SELECT AddressBook_CountryID FROM AddressBook WHERE (AddressBook_Kid = '" & kid.Trim & "')")
        Dim State As String = ReturnValue("SELECT AddressBook_StateID FROM AddressBook WHERE (AddressBook_Kid = '" & kid.Trim & "')")
        Dim City As String = ReturnValue("SELECT AddressBook_CityID FROM AddressBook WHERE (AddressBook_Kid = '" & kid.Trim & "')")

        If Not drpCountry Is Nothing Then
            Fill_Combo("SELECT DISTINCT Country_Kid, Country_Name FROM Country_Master WHERE (Country_IsDeleted = '0')", drpCountry)
        End If

        drpCountry.Items.FindByText("India").Selected = True
        strquery = "select Country_ISDCode from Country_Master where Country_Kid='" & drpCountry.SelectedValue & "'"
        txttcode.Text = ReturnValue(strquery)
        txtmcode.Text = txttcode.Text

        strquery = "SELECT DISTINCT State_Kid, State_Name FROM State_Master WHERE (State_IsDeleted = '0') and State_CountryID='" & country & "'"
        If Not drpState Is Nothing Then
            Fill_Combo(strquery, drpState)
        End If

        strquery = "SELECT DISTINCT City_Kid, City_Name FROM City_Master WHERE (City_IsDeleted = '0') and City_StateID='" & State & "'"
        If Not drpCity Is Nothing Then
            Fill_Combo(strquery, drpCity)
        End If
    End Sub

    ' code to update the address of particular user
    Protected Sub btnUpdate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
        Dim UserName As String = txtusername.Text
        Dim address As String = txtaddress.Text
        Dim zipcode As String = txtZipCode.Text
        Dim TelNo As String = txttcode.Text & "-" & txtcitycode.Text & "-" & txtTelNo.Text
        Dim MobNo As String = txtmcode.Text & "-" & txtMobNo.Text
        Dim email As String = txtEmail.Text
        Dim Extno As String = txtextno.Text

        Dim country As String = drpCountry.SelectedValue
        Dim state As String = drpState.SelectedValue
        Dim city As String = drpCity.SelectedValue
        Dim AddId As String = ddShipName.SelectedValue
        query = "update AddressBook set AddressBook_UserName='" & UserName & "',AddressBook_Add1='" & address & "',AddressBook_CityID='" & drpCity.SelectedValue & "',AddressBook_StateID='" & drpState.SelectedValue & "',AddressBook_CountryID='" & drpCountry.SelectedValue & "',AddressBook_Zipcode='" & zipcode & "',AddressBook_TelExtn='" & Extno & "',AddressBook_TelNumber='" & TelNo & "',AddressBook_MobNumber='" & MobNo & "',AddressBook_Email='" & email & "' where AddressBook_Kid='" & AddId & "'"
        Dim cmd As New SqlCommand
        Dim SqlCon As New SqlConnection(ConfigurationManager.AppSettings("ConnectionString"))
        cmd.CommandText = query
        cmd.Connection = SqlCon

        SqlCon.Open()
        cmd.ExecuteNonQuery()
        objPL.getcmbData(Session("BuyId"), ddShipName)       ' function to bind the dropdown list
        ddShipName.Items.FindByValue(AddId).Selected = True
        lblAddress.Visible = True
        GetAdd1(Session("BuyId"), ddShipName.SelectedValue)   ' function to bind the address to the lbladdress
        SqlCon.Close()
        cmd.Dispose()
        SqlCon.Dispose()
        If ddShipName.SelectedIndex <> 0 Then
            lblAddress.Visible = True
        End If
        If ViewState.Item("TOS") = "M" Then             ' to check for the mulitship
            table1.Visible = True
        End If
        ddShipName.Visible = True
        btnUpdate.Visible = False
        getAddress(ddShipName.SelectedItem.Value)       ' bind lbladdress for billing address or shiping address
        pnladdress.Visible = False
        ddShipName.Enabled = True
        clearfields()

    End Sub
    ' function to clear the fields
    Function clearfields()
        txtusername.Text = ""
        txtaddress.Text = ""
        txtZipCode.Text = ""
        txtTelNo.Text = ""
        txtMobNo.Text = ""
        txtEmail.Text = ""
        txtextno.Text = ""
        txtcitycode.Text = ""
        drpCountry.SelectedIndex = -1
        drpState.SelectedIndex = -1
        drpCity.SelectedIndex = -1
    End Function

    'code to click the open address book form for add new address
    Protected Sub hypNewAdd_Click1(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles hypNewAdd.Click
        If ddShipName.SelectedIndex <> 0 Then
            lblAddress.Visible = True
        Else
            lblAddress.Visible = False
        End If

        lblerror.Visible = False
        ddShipName.Enabled = False
        pnladdress.Visible = True
        btnInsert.Visible = True
        btnUpdate.Visible = False
        fillCombos()
        clearfields()
    End Sub
    'code to click the open address book form for update address
    Protected Sub hypupdate_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles hypupdate.Click
        If ddShipName.SelectedIndex = 0 Then
            lblerror.Visible = True
            lblerror.Text = "Please Select Address !!"
            table1.Visible = False
            lblAddress.Visible = False
        Else
            lblerror.Visible = False
            ddShipName.Enabled = False
            pnladdress.Visible = True
            btnUpdate.Visible = True
            btnInsert.Visible = False
            GetUpdatedata(Session("BuyId"), ddShipName.SelectedValue)
        End If
    End Sub
    ' 
    Function singlshiptable()
        Dim i As Integer
        dtSingleTemp()
        'For i = 0 To ds.Tables(0).Rows.Count - 1
        Dim gvrow As GridViewRow
        For Each gvrow In gvvat.Rows
            drow = SingleShipTable.NewRow
            drow("ProductName") = gvrow.Cells(1).ToString 'ds.Tables(0).Rows(i).Item("Product_Name").ToString
            drow("ProductId") = gvrow.Cells(0).ToString 'ds.Tables(0).Rows(i).Item("Product_Kid").ToString
            drow("Quantity") = gvrow.Cells(10).ToString 'ds.Tables(0).Rows(i).Item("ShopCart_Quantity").ToString
            drow("Shipping Address") = ""
            drow("ShippingId") = ""
            drow("Special Price") = "" 'ds.Tables(0).Rows(i).Item("ShopCart_SpecialPrice").ToString
            drow("NetAmount") = gvrow.Cells(11).ToString 'ds.Tables(0).Rows(i).Item("ShopCart_SpecialPrice").ToString * ds.Tables(0).Rows(i).Item("ShopCart_Quantity").ToString
            drow("CityId") = ""


            drow("SupplierId") = "" 'ds.Tables(0).Rows(i).Item("Product_SupplierId").ToString

            drow("UserName") = ""

            SingleShipTable.Rows.Add(drow)

        Next

    End Function
    ' function for single shipping that is used in payment table
    Protected Function dtSingleTemp() As DataTable
        SingleShipTable.Columns.Clear()

        With SingleShipTable.Columns
            .Add("ProductName", GetType(System.String))
            .Add("ProductId", GetType(System.String))
            .Add("Quantity", GetType(System.String))
            .Add("Shipping Address", GetType(System.String))
            .Add("ShippingId", GetType(System.String))
            .Add("Special Price", GetType(System.Decimal))
            .Add("NetAmount", GetType(System.Decimal))
            .Add("CityId", GetType(System.String))
            .Add("stateId", GetType(System.String))
            .Add("SupplierId", GetType(System.String))
            .Add("UserName", GetType(System.String))
        End With
        Return SingleShipTable
    End Function

    Protected Sub GvMultipleShip_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GvMultipleShip.PageIndexChanging
        GvMultipleShip.PageIndex = e.NewPageIndex
        GvMultipleShip.DataSource = MultipleShipTable
        GvMultipleShip.DataBind()
    End Sub

    Protected Sub GvMultipleShip_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GvMultipleShip.RowDataBound
        'Dim lblname As Label = CType(GvMultipleShip.TemplateControl.FindControl("lblname"), Label)
        'lblname.Text = ddShipName.SelectedItem.Text

    End Sub
    ' function to find city and address
    Function findcityaddress()
        Dim cityid As String = ""
        Dim stateid As String = "'"
        Dim str As String = "select AddressBook_Add1,AddressBook_CityID,AddressBook_StateID from AddressBook where AddressBook_Kid='" & ddShipName.SelectedValue & "'"
        con.Open()
        Dim cmd As New SqlCommand(str, con)
        Dim dr As SqlDataReader
        dr = cmd.ExecuteReader
        Dim shippaddress As String = ""
        If dr.Read Then
            'drow("Shipping Address") = CType(GvLocation.SelectedRow.FindControl("lblShippingAdress"), Label).Text

            drow("Shipping Address") = dr(0).ToString
            shippaddress = dr(0).ToString
            drow("ShippingId") = ddShipName.SelectedValue
            'drow("CityId") = GvLocation.SelectedRow.Cells(12).Text
            'drow("stateId") = GvLocation.SelectedRow.Cells(9).Text
            drow("CityId") = dr(1).ToString
            cityid = dr(1).ToString
            drow("stateId") = dr(2).ToString
            stateid = dr(2).ToString
        End If
        dr.Close()
        str = "select City_Name from City_Master where City_Kid='" & cityid & "'"

        cmd = New SqlCommand(str, con)

        dr = cmd.ExecuteReader
        Dim cityname As String = ""
        If dr.Read Then
            cityname = dr(0).ToString
        End If
        dr.Close()
        str = "select State_Name from State_Master where State_Kid='" & stateid & "'"

        cmd = New SqlCommand(str, con)

        dr = cmd.ExecuteReader
        If dr.Read Then
            'statename = dr(0).ToString
            drow("StateName") = dr(0).ToString.Trim
        End If
        dr.Close()
        drow("UserName") = ddShipName.SelectedItem.Text & " , " & shippaddress & " , " & cityname
        cmd.Dispose()
        con.Close()

    End Function

    Function bindtaxtable(ByVal count As Integer)
        Taxtable.Rows.Clear()
        Taxtable.Columns.Clear()
        With Taxtable.Columns
            .Add("TaxID", GetType(System.String))
            .Add("TaxForm", GetType(System.String))
        End With
        Dim dtrow As DataRow = Taxtable.NewRow
        'Dim s As String = "SELECT    Tax_Form,Tax_Kid FROM         TaxMaster where Tax_ProductId='" & DropDownList1.SelectedValue & "' and Tax_StateId='" & drow("stateId").ToString & "'"
        Dim s As String = "SELECT    Tax_Form,Tax_Kid FROM         TaxMaster where Tax_ProductId='" & GvMultipleShip.Rows(count).Cells(1).Text & "' and Tax_StateId='" & GvMultipleShip.Rows(count).Cells(7).Text.ToString & "'"

        con.Open()
        cmd = New SqlCommand(s, con)
        dr = cmd.ExecuteReader
        While dr.Read
            dtrow("TaxForm") = dr(0).ToString
            dtrow("TaxID") = dr(1).ToString
            Taxtable.Rows.Add(dtrow)
        End While
        Dim ddl As DropDownList
        ddl = CType(GvMultipleShip.Rows(count).Cells(10).FindControl("drpselectexemp"), DropDownList)
        ddl.Items.Clear()
        ddl.DataSource = Taxtable
        ddl.DataTextField = "TaxForm"
        ddl.DataValueField = "TaxId"
        ddl.DataBind()
        con.Close()
    End Function
    ' function to bind the vattax to display calculate excite duty,vat ,cst  for Single shipping
    Function functionbindtaxvat()
        Try

            vattable.Rows.Clear()
            Con.Open()
            If ViewState.Item("TOS") = "S" Then
                Dim gvrow As GridViewRow
                For Each gvrow In dgBill.Rows
                    Dim lblprod As Label = CType(gvrow.FindControl("lblproductid"), Label) ' find lable for product id
                    Dim lblqty As Label = CType(gvrow.FindControl("Label1"), Label)     ' find label for shop cart quantity
                    Dim image1 As Image = CType(gvrow.FindControl("Imagebutton1"), Image)
                    Dim imagename As Array = Split(image1.ImageUrl, "/")
                    Dim str As String = "SELECT   ProductVat_ExciseDuty, ProductVat_EduCess,  ProductVat_VAT, ProductVat_CST, ProductVat_CSTAgainstC, ProductVat_SalesTaxRemark FROM ProductVat where  ProductVat_ProductId='" & lblprod.Text.ToString & "'"
                    cmd = New SqlCommand(str, Con)
                    dr = cmd.ExecuteReader
                    If dr.Read Then

                        Dim dtrow As DataRow = vattable.NewRow
                        dtrow("Product_Kid") = lblprod.Text.ToString        'Product_Kid
                        dtrow("Product_Name") = gvrow.Cells(2).Text         'Product_Name
                        dtrow("Product_AtcoPrice") = gvrow.Cells(3).Text  'Product_AtcoPrice
                        Dim exdt As Decimal = (dr(0).ToString * gvrow.Cells(3).Text) / 100
                        dtrow("ProductVat_ExciseDuty") = FormatNumber(exdt, 2)
                        Dim educess As Double = (exdt * dr(1).ToString) / 100
                        dtrow("ProductVat_EduCess") = FormatNumber(educess, 2)
                        Dim vat As Decimal = gvrow.Cells(3).Text + exdt + educess
                        If Session("statename").ToString.Trim = "Gujarat" Then ' check for shipping addres is gujarat
                            gvvat.Columns(8).Visible = True
                            dtrow("ProductVat_VAT") = FormatNumber(((vat * dr(2).ToString) / 100), 2)
                            dtrow("ProductVat_CST") = 0
                            dtrow("ProductVat_CSTAgainstC") = 0
                            gvvat.Columns(8).Visible = False
                        Else
                            gvvat.Columns(8).Visible = True
                            gvvat.Columns(13).Visible = True
                            dtrow("ProductVat_VAT") = 0
                            dtrow("ProductVat_CST") = FormatNumber((Val(dr(3).ToString) * vat), 2) / 100
                            dtrow("ProductVat_CSTAgainstC") = 0
                        End If

                        dtrow("ProductVat_CST1") = FormatNumber((Val(dr(3).ToString) * vat), 2) / 100
                        dtrow("ProductVat_CSTAgainstC1") = FormatNumber((Val(dr(4).ToString) * vat), 2) / 100
                        dtrow("ProductVat_Qty") = Val(lblqty.Text)
                        dtrow("ProductVat_TotalPrice") = FormatNumber(vat + dtrow("ProductVat_VAT") + dtrow("ProductVat_CST"), 2)
                        dtrow("ProductVat_NetAmt") = FormatNumber(Val(lblqty.Text) * dtrow("ProductVat_TotalPrice"), 2)
                        dtrow("ProductVat_Address") = ""
                        dtrow("Product_Code") = gvrow.Cells(1).Text
                        dtrow("Product_Image") = imagename(4).ToString

                        vattable.Rows.Add(dtrow)

                    Else
                        If Session("statename").ToString.Trim = "Gujarat" Then
                            gvvat.Columns(8).Visible = False
                        Else
                            gvvat.Columns(8).Visible = True
                        End If

                        Dim dtrow As DataRow = vattable.NewRow

                        dtrow("Product_Kid") = lblprod.Text.ToString        'Product_Kid
                        dtrow("Product_Name") = gvrow.Cells(2).Text         'Product_Name
                        dtrow("Product_AtcoPrice") = gvrow.Cells(3).Text  'Product_AtcoPrice
                        dtrow("ProductVat_Qty") = Val(lblqty.Text)
                        dtrow("ProductVat_NetAmt") = FormatNumber(Val(lblqty.Text) * dtrow("Product_AtcoPrice"), 2)
                        dtrow("ProductVat_Address") = ""
                        dtrow("Product_Code") = gvrow.Cells(1).Text
                        dtrow("Product_Image") = imagename(4).ToString
                        vattable.Rows.Add(dtrow)

                    End If
                    dr.Close()
                Next
            End If
            Con.Close()
            gvvat.Columns(2).Visible = True
            gvvat.Columns(14).Visible = True
            gvvat.Columns(15).Visible = True
            gvvat.Columns(16).Visible = True
            gvvat.DataSource = vattable
            gvvat.DataBind()
            gvvat.Columns(2).Visible = False
            gvvat.Columns(14).Visible = False
            gvvat.Columns(15).Visible = False
            gvvat.Columns(16).Visible = False
            dgBill.Visible = False

            Dim gvvatrow As GridViewRow
            For Each gvvatrow In gvvat.Rows
                Dim lb As Label = CType(gvvatrow.FindControl("lblvat"), Label)
                Dim ch As CheckBox = CType(gvvatrow.FindControl("CheckBox1"), CheckBox)
                Try
                    If lb.Text <> 0 Then
                        ch.Enabled = False
                    Else
                        ch.Enabled = True
                    End If
                Catch ex As Exception
                    ch.Enabled = False

                End Try
            Next
            Session("SingleShippTabel") = vattable 'This session is used in paymentdetails.aspx form for single shipping
        Catch ex As Exception

        End Try
    End Function
    ' function to bind the vattax to display calculate excite duty,vat ,cst  for multiple shipping
    Function functionbindtaxvat(ByVal count As Integer)
        Try

        
            Con.Open()
            If ViewState.Item("TOS") = "M" Then

                ' Dim str As String = "SELECT   ProductVat_ExciseDuty, ProductVat_EduCess,  ProductVat_VAT, ProductVat_CST, ProductVat_CSTAgainstC, ProductVat_SalesTaxRemark FROM ProductVat where  ProductVat_ProductId='" & GvMultipleShip.Rows(count).Cells(1).Text & "'"
                Dim str As String = "select   ProductVat.ProductVat_ExciseDuty, ProductVat.ProductVat_EduCess, ProductVat.ProductVat_VAT, ProductVat.ProductVat_CST,ProductVat.ProductVat_CSTAgainstC, ProductVat.ProductVat_SalesTaxRemark, Product_Master.Product_Code, Product_Master.Product_Image FROM    ProductVat INNER JOIN Product_Master ON ProductVat.ProductVat_ProductId = Product_Master.Product_Kid  WHERE ProductVat.ProductVat_ProductId='" & GvMultipleShip.Rows(count).Cells(1).Text & "'"
                cmd = New SqlCommand(str, Con)
                dr = cmd.ExecuteReader
                If dr.Read Then

                    Dim dtrow As DataRow = vattable.NewRow
                    dtrow("Product_Kid") = GvMultipleShip.Rows(count).Cells(1).Text        'Product_Kid
                    dtrow("Product_Name") = GvMultipleShip.Rows(count).Cells(0).Text         'Product_Name
                    dtrow("Product_AtcoPrice") = GvMultipleShip.Rows(count).Cells(4).Text 'Product_AtcoPrice
                    Dim exdt As Decimal = (dr(0).ToString * Val(GvMultipleShip.Rows(count).Cells(4).Text)) / 100
                    dtrow("ProductVat_ExciseDuty") = FormatNumber(exdt, 2)
                    Dim educess As Double = FormatNumber((exdt * Val(dr(1).ToString)), 2) / 100
                    dtrow("ProductVat_EduCess") = FormatNumber(educess, 2)
                    Dim vat As Decimal = Val(GvMultipleShip.Rows(count).Cells(4).Text) + exdt + educess

                    If GvMultipleShip.Rows(count).Cells(11).Text.Trim = "Gujarat" Then           ' check for shipping addres is gujarat
                        dtrow("ProductVat_VAT") = FormatNumber((Val(vat) * Val(dr(2).ToString)) / 100, 2)
                        dtrow("ProductVat_CST") = 0
                        dtrow("ProductVat_CSTAgainstC") = 0

                    Else

                        dtrow("ProductVat_VAT") = 0
                        dtrow("ProductVat_CST") = FormatNumber((Val(dr(3).ToString) * vat) / 100, 2)
                        dtrow("ProductVat_CSTAgainstC") = 0

                    End If
                    dtrow("ProductVat_CST1") = FormatNumber((Val(dr(3).ToString) * vat) / 100, 2)
                    dtrow("ProductVat_CSTAgainstC1") = FormatNumber((Val(dr(4).ToString) * vat) / 100, 2)
                    dtrow("ProductVat_Qty") = Val(GvMultipleShip.Rows(count).Cells(2).Text)
                    dtrow("ProductVat_TotalPrice") = FormatNumber(vat + dtrow("ProductVat_VAT") + dtrow("ProductVat_CST"), 2)
                    dtrow("ProductVat_NetAmt") = FormatNumber(Val(GvMultipleShip.Rows(count).Cells(2).Text) * dtrow("ProductVat_TotalPrice"), 2)
                    Dim lblname As Label = CType(GvMultipleShip.Rows(count).FindControl("lblname"), Label) ' find lable for shipping address of multiple shipping
                    dtrow("ProductVat_Address") = lblname.Text.Trim
                    dtrow("Product_Code") = dr(6).ToString
                    dtrow("Product_Image") = dr(7).ToString


                    vattable.Rows.Add(dtrow)


                Else
                    dr.Close()
                    Dim drtemp As SqlDataReader
                    str = "select Product_Code, Product_Image FROM    Product_Master where Product_Kid ='" & GvMultipleShip.Rows(count).Cells(1).Text & "'"
                    cmd = New SqlCommand(str, Con)
                    drtemp = cmd.ExecuteReader
                    If drtemp.Read Then
                        Dim dtrow As DataRow = vattable.NewRow

                        dtrow("Product_Kid") = GvMultipleShip.Rows(count).Cells(1).Text        'Product_Kid
                        dtrow("Product_Name") = GvMultipleShip.Rows(count).Cells(0).Text         'Product_Name
                        dtrow("Product_AtcoPrice") = GvMultipleShip.Rows(count).Cells(4).Text 'Product_AtcoPrice
                        dtrow("ProductVat_Qty") = Val(GvMultipleShip.Rows(count).Cells(2).Text)
                        dtrow("ProductVat_NetAmt") = FormatNumber(Val(GvMultipleShip.Rows(count).Cells(2).Text) * dtrow("Product_AtcoPrice"), 2)
                        Dim lblname As Label = CType(GvMultipleShip.Rows(count).FindControl("lblname"), Label) ' find lable for shipping address of multiple shipping
                        dtrow("ProductVat_Address") = lblname.Text.Trim
                        dtrow("Product_Code") = drtemp(0).ToString
                        dtrow("Product_Image") = drtemp(1).ToString

                        vattable.Rows.Add(dtrow)
                        drtemp.Close()
                    End If

                End If
                dr.Close()
            End If
            Con.Close()
            gvvat.Columns(2).Visible = True
            gvvat.Columns(14).Visible = True
            gvvat.Columns(15).Visible = True

            gvvat.DataSource = vattable
            gvvat.DataBind()
            gvvat.Columns(2).Visible = False
            gvvat.Columns(14).Visible = False
            gvvat.Columns(15).Visible = False

            '  Dim ch As CheckBox = CType(gvvat.Rows(count).FindControl("CheckBox1"), CheckBox)
            '  ch.Enabled = False

            Dim gvvatrow As GridViewRow
            For Each gvvatrow In gvvat.Rows
                Dim lb As Label = CType(gvvatrow.FindControl("lblvat"), Label)
                Dim ch As CheckBox = CType(gvvatrow.FindControl("CheckBox1"), CheckBox)
                Try
                    If lb.Text <> 0 Then
                        ch.Enabled = False
                    Else
                        ch.Enabled = True
                    End If
                Catch ex As Exception
                    ch.Enabled = False

                End Try


            Next
            Session("Shippdetail") = vattable 'This session is used in paymentdetails.aspx form for Multiple shipping
        Catch ex As Exception

        End Try

    End Function
    ' Create dynamic table vattable to calculate excite duty,vat ,cst 

    Function createvatdynamictable()
        With vattable.Columns
             .Add("Product_Kid", GetType(System.String))
            .Add("Product_Name", GetType(System.String))
            .Add("Product_AtcoPrice", GetType(System.String))
            .Add("ProductVat_ExciseDuty", GetType(System.String))
            .Add("ProductVat_EduCess", GetType(System.String))
            .Add("ProductVat_VAT", GetType(System.String))
            .Add("ProductVat_CST", GetType(System.String))
            .Add("ProductVat_CSTAgainstC", GetType(System.String))
            .Add("ProductVat_CST1", GetType(System.String))
            .Add("ProductVat_CSTAgainstC1", GetType(System.String))
            .Add("ProductVat_Qty", GetType(System.String))
            .Add("ProductVat_TotalPrice", GetType(System.String))
            .Add("ProductVat_NetAmt", GetType(System.String))
            .Add("ProductVat_Address", GetType(System.String))
            .Add("Product_Code", GetType(System.String))
            .Add("Product_Image", GetType(System.String))

        End With
    End Function
    Protected Sub dgBill_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dgBill.SelectedIndexChanged

    End Sub

    Protected Sub GvMultipleShip_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles GvMultipleShip.SelectedIndexChanged

    End Sub

    Protected Sub gvvat_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gvvat.SelectedIndexChanged

    End Sub

    ' this checkbox of vaxtax to display the cst or cst against value.
    Protected Sub CheckBox1_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Try

        
            Dim vattable As DataTable

            If ViewState.Item("TOS") = "S" Then
                vattable = Session("SingleShippTabel")

            ElseIf ViewState.Item("TOS") = "M" Then
                vattable = Session("Shippdetail")
            End If

            Dim i As Integer = 0
            Dim gvrow As GridViewRow
            For Each gvrow In gvvat.Rows
                Dim ch As CheckBox = CType(gvrow.FindControl("CheckBox1"), CheckBox)
                Dim lblcst As Label = CType(gvrow.FindControl("lblCST1"), Label)
                Dim lblcstcform As Label = CType(gvrow.FindControl("lblCSTAgainst1"), Label)
                Dim lblTotalPrice As Label = CType(gvrow.FindControl("lblTotalPrice"), Label)
                Dim lbltotalamt As Label = CType(gvrow.FindControl("lbltotalamt"), Label)
                Dim lblAtcomaarPrice As Label = CType(gvrow.FindControl("lblAtcomaarPrice"), Label)
                Dim lblExciseDuty As Label = CType(gvrow.FindControl("lblExciseDuty"), Label)
                Dim lblEduCsse As Label = CType(gvrow.FindControl("lblEduCsse"), Label)
                Dim lblvat As Label = CType(gvrow.FindControl("lblvat"), Label)
                Dim lblQty As Label = CType(gvrow.FindControl("lblQty"), Label)
                If ch.Enabled = True Then
                    If ch.Checked = True Then
                        'gvrow.Cells(8).Text = lblcstcform.Text
                        CType(gvrow.FindControl("lblCSTAgainst"), Label).Text = FormatNumber(lblcstcform.Text, 2)
                        CType(gvrow.FindControl("lblCST"), Label).Text = 0

                        'gvrow.Cells(7).Text = 0
                        'lblcstcform.Text = 0
                    Else
                        'gvrow.Cells(8).Text = 0
                        'gvrow.Cells(7).Text = lblcst.Text
                        CType(gvrow.FindControl("lblCSTAgainst"), Label).Text = 0
                        Try
                            CType(gvrow.FindControl("lblCST"), Label).Text = FormatNumber(lblcst.Text, 2)
                        Catch ex As Exception

                        End Try
                    End If
                    Dim totalprice As Double = Val(lblAtcomaarPrice.Text) + Val(lblExciseDuty.Text) + Val(lblEduCsse.Text) + Val(lblvat.Text) + Val(CType(gvrow.FindControl("lblCST"), Label).Text) + Val(CType(gvrow.FindControl("lblCSTAgainst"), Label).Text)
                    CType(gvrow.FindControl("lblTotalPrice"), Label).Text = FormatNumber(totalprice, 2)
                    Dim totalamt As Decimal = FormatNumber(Val(totalprice) * Val(lblQty.Text), 2)
                    CType(gvrow.FindControl("lbltotalamt"), Label).Text = totalamt


                    vattable.Rows(i).Item(11) = totalprice.ToString

                    vattable.Rows(i).Item(12) = totalamt.ToString


                    'lblcst.Text = 0
                End If
                i = i + 1


            Next
            If ViewState.Item("TOS") = "S" Then
                Session("SingleShippTabel") = vattable

            ElseIf ViewState.Item("TOS") = "M" Then
                Session("Shippdetail") = vattable
            End If

       
        Catch ex As Exception

        End Try


    End Sub
End Class
