Avatar of Brian
BrianFlag for United States of America asked on

GridView PageIndexChanging

Hi,

I have a problem with my PageIndexChanging code. When my page first load i have code that executes on the Page_Load Event that retries data to a dropdown. When I select a value from the dropdown control it populates a GridView. When I try to select a different page within the Paging of the GridView i do not see the results nor do i receive an error.



Please see my code below:

 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then

      'Binds data to DropDownList1
     
  End If
    End Sub


Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged

'Binds results from DropDown and displays the values in the GridView

End Sub


Protected Sub GridView1_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridView1.PageIndexChanging
        GridView1.PageIndex = e.NewPageIndex
        GridView1.DataBind()
    End Sub
ASP.NET

Avatar of undefined
Last Comment
Brian

8/22/2022 - Mon
rstomar

Where do you assign the datasource for the grid view? I assume in DropDownList1_SelectedIndexChanged so, you need to assign the datasource to the gridview on each postback.

In order to do that you may want to use selected dropdown value and reassign the datasource for the gridview in PageLoad on Ispostback = true

like as follows :

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then

      'Binds data to DropDownList1

      Else
           'Binds results from DropDown and displays the values in the GridView
      End If

    End Sub


Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged

'Binds results from DropDown and displays the values in the GridView

End Sub


Protected Sub GridView1_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridView1.PageIndexChanging
        GridView1.PageIndex = e.NewPageIndex
        GridView1.DataBind()
    End Sub


funwithdotnet

I like to do something like: (code attached.)

As you can see, you do not need to bind the GridView on each postback. If the GridView depends on a selection from the DropDownList, you do not bind the GridView in the initial page load.

Once the GridView has been databound (i'm assuming in response to a selectedIndex_Changed event), it will retain its viewstate by default and does not need to be re-bound unless a change is made (like a DropDownList selection, changing the page index or sorting.) In that case, set the page index and databind().

Make sure  to set the PageIndex = 0 when binding in response to a SelectedIndex_Changed event or changing the sort. You already know what to do for the PageIndex_Changing event.



Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
	If Not IsPostBack Then
		InitializePage()
	End If
End Sub
 
Private Sub InitializePage()
	GridView1.SelectedIndex = 0
	GridView1.Visible = False
	DropDownList1_DataBind() ' runs method that binds a datasource to the dropdownlist
End Sub
 
Private Sub GridView1_Refresh(ByVal pageIndex As Integer)
	If GroupDropDownList.SelectedIndex > 0 Then
		GridView1_DataBind() ' runs method that binds a datasource to the gridview based on the value of the dropdownlist.
	Else
		GridView1.Visible = False
	End If
End Sub
 
Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged
	' Do something, then ...
	GridView1_Refresh(0) ' always reset to the first page when changing the datasource
End Sub
 
Private Sub GridView1_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridView1.PageIndexChanging
	GridView1_Refresh(e.NewPageIndex)
End Sub

Open in new window

ASKER
Brian

Sorry, I understand what you mean just not sure how to implement that in my current code. Please see the change that I added from your post, its at the bottom and commented out.

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            Dim MyReader As SqlDataReader

            ' Define data objects
            Dim conn As SqlConnection
            Dim NetworkComm As SqlCommand

            ' Read the connection string from Web.config
            Dim connectionString As String = ConfigurationManager.ConnectionStrings("NNDS_IP").ConnectionString

            ' Initialize connection
            conn = New SqlConnection(connectionString)

            ' Create command for Student
            NetworkComm = New SqlCommand("SelectNetwork", conn)
            ' Specify we're calling a stored procedure
            NetworkComm.CommandType = CommandType.StoredProcedure

            Try
                ' Open the connection
                NetworkComm.Connection.Open()
                MyReader = NetworkComm.ExecuteReader(CommandBehavior.CloseConnection)

                ' Populate the Entity Dropdown
                DropDownList1.DataSource = MyReader
                DropDownList1.DataValueField = "NETWORKID"
                DropDownList1.DataTextField = "NETWORKNAME"
                DropDownList1.DataBind()

            Finally
                ' Close the connection
                NetworkComm.Dispose()
                conn.Dispose()
            End Try

        Else

            ' Is this where i need to add this part at?
            ' I also get an error that says Name 'NetworkIPID' is not declared
            GridView1.DataSource = NetworkIPID.Tables(0)
            GridView1.DataBind()

        End If
    End Sub
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
ASKER
Brian

funwithdotnet,

Sorry, but i'm confused with what you provided. NOT your fault, but i'm still somewhat of a newbie. I'm learning though but not an ace like you guys, that is my goal though:) I understand with the way my code is now and would like to implement this with what i have or even change a "few" things around to make it work. I will attach my codebehind and maybe it's just a small change that i need to make:)
eecode.txt
rstomar

Yes you placed it correctly.
whatever you have in DropDownList1_SelectedIndexChanged() block to populate gridview should go in the Else part of PageLoad. (including the variable declarations)

I assume that in DropDownList1_SelectedIndexChanged()  function you are getting the data based on drop down selection in a dataset. and then assign that dataset to the Gridview1.DataSource.
So do the same stuff in Else block too.

rstomar

Imports System.Data
Imports System.Data.Sql
Imports System.Data.SqlClient
Imports System.Configuration

Partial Class servers_subnetServers
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            Dim MyReader As SqlDataReader

            ' Define data objects
            Dim conn As SqlConnection
            Dim NetworkComm As SqlCommand

            ' Read the connection string from Web.config
            Dim connectionString As String = ConfigurationManager.ConnectionStrings("NNDS_IP").ConnectionString

            ' Initialize connection
            conn = New SqlConnection(connectionString)

            ' Create command for Student
            NetworkComm = New SqlCommand("SelectNetwork", conn)
            ' Specify we're calling a stored procedure
            NetworkComm.CommandType = CommandType.StoredProcedure

            Try
                ' Open the connection
                NetworkComm.Connection.Open()
                MyReader = NetworkComm.ExecuteReader(CommandBehavior.CloseConnection)

                ' Populate the Entity Dropdown
                DropDownList1.DataSource = MyReader
                DropDownList1.DataValueField = "NETWORKID"
                DropDownList1.DataTextField = "NETWORKNAME"
                DropDownList1.DataBind()

            Finally
                ' Close the connection
                NetworkComm.Dispose()
                conn.Dispose()
            End Try

      Else
            RefreshGrid(DropDownList1.SelectedValue)

        End If

    End Sub

Private Sub RefreshGrid(selValue as Int32)
      Dim conn As SqlConnection
        Dim NetworkIPIDComm As SqlCommand
        Dim adapter As SqlDataAdapter
        Dim NetworkIPID As DataSet = New DataSet("NetworkIPID")

        ' Read the connection string from Web.config
        Dim connectionString As String = ConfigurationManager.ConnectionStrings("NNDS_IP").ConnectionString

        ' Initialize connection
        conn = New SqlConnection(connectionString)

        ' Create command for SubnetList
        NetworkIPIDComm = New SqlCommand("subnetServer", conn)
        ' Specify we're calling a stored procedure
        NetworkIPIDComm.CommandType = System.Data.CommandType.StoredProcedure

        ' Enclose database code in Try-Catch-Finally
        Try
            ' Open the connection
            conn.Open()

            NetworkIPIDComm.Parameters.Add("@networkid", SqlDbType.Int)
            NetworkIPIDComm.Parameters("@networkid").Value = selValue
            ' Execute the command
            adapter = New SqlDataAdapter
            adapter.TableMappings.Add("Table", "NetworkIPID")
            adapter.SelectCommand = NetworkIPIDComm
            adapter.Fill(NetworkIPID)
            ' Close the reader        

            ' Populate the list of subjects
            GridView1.DataSource = NetworkIPID.Tables(0)
            GridView1.DataBind()

        Finally
            ' Close the connection
            conn.Close()
        End Try
End Sub

    Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged

        RefreshGrid(DropDownList1.SelectedValue)
    End Sub

    Protected Sub GridView1_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridView1.PageIndexChanging
        GridView1.PageIndex = e.NewPageIndex
        GridView1.DataBind()
    End Sub
End Class
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
rstomar

changed the code in notepad...so there may be syntax errors ,but, this is how it should look.
ASKER
Brian

rstomar,

WOW, that worked and there where no syntax errors:) :) Now, can you explain very briefly the deference between Private and Protected?

Also, not sure how this works can you explain in "Newbie" terms:) I like how this code looks now, it seems more clean and less code:)

I'm primarily confused with the following events below:

Private Sub RefreshGrid(ByVal selValue As Int32)
and
Protected Sub DropDownList1_SelectedIndexChanged
ASKER CERTIFIED SOLUTION
rstomar

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
ASKER
Brian

Thank you very much for your help and explaining this to me. It was greatly appreciated:)
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck