Partial Class EditSettings
    Inherits AdminPage

    Private m_ViewKey As String = "ESSQL"

    Protected Sub btnPage_Click(sender As Object, e As System.EventArgs) Handles btnPage.Click
        If IsNumeric(txtPage.Text) AndAlso _
            (Not (String.IsNullOrEmpty(txtPage.Text))) Then
            GridView1.PageIndex = txtPage.Text
            GridView1.DataBind()
        End If
    End Sub

    Protected Sub btnFilter_Click(sender As Object, e As System.EventArgs) Handles btnFilter.Click
        BindData()
        GridView1.SetPageIndex(0)
    End Sub

    Protected Sub GridView1_PageIndexChanged(sender As Object, e As System.EventArgs) Handles GridView1.PageIndexChanged
        BindData()
    End Sub

    Private Sub BindData()
        ApplyFilters()
        GridView1.DataSourceID = "SqlDataSource1"
        GridView1.DataBind()
    End Sub

    Private Sub ApplyFilters()
        Dim strFilter As String = ""
        If (ddlEnvironment.SelectedIndex > 0) Then
            AppendCondition("EnvironmentName", ddlEnvironment.Text, strFilter)
        End If

        AppendCondition("ProviderName", txtProvider.Text, strFilter)
        AppendCondition("SettingName", txtSetting.Text, strFilter)
        AppendCondition("SettingValue", txtValue.Text, strFilter)

        strFilter &= " 1=1 "
        strFilter = "SELECT * FROM [ADMIN].[Provider_Settings] " & "WHERE " & strFilter

        SqlDataSource1.SelectCommand = strFilter
        SqlDataSource1.Select(DataSourceSelectArguments.Empty)
        lblFilter.Text = strFilter

        ViewState(m_ViewKey) = strFilter
    End Sub

    Private Sub AppendCondition(ByVal psDBField As String, _
                                ByVal psValue As String, _
                                ByRef psFilter As String)
        If (Not (String.IsNullOrEmpty(psValue))) Then
            psFilter &= " " & psDBField & "  like '%" & psValue & "%' and "
        End If
    End Sub

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        Dim sSQL As String

        If IsNothing(ViewState(m_ViewKey)) Then
            ApplyFilters()
        End If

        If Me.IsPostBack() Then
            sSQL = ViewState(m_ViewKey)
            SqlDataSource1.SelectCommand = sSQL
            lblFilter.Text = sSQL
        End If
    End Sub
End Class