datagrid error on change page (VB.ASP.NET)

  • Thread starter Mad Scientist Jr
  • Start date
M

Mad Scientist Jr

I am getting an error in my code that references a textbox inside the
current row of my datagrid, whenever I try changing the page (paging is
enabled). This code doesn't even run unless a button in the datagrid is
clicked, but is erroring out the page when I click page 2,3,etc.

I have tried a few different notations without any luck. Can someone
look at the lines below and tell me what might be wrong? Thanks in
advance!

'event being used to change page:
Private Sub DataGrid1_PageIndexChanged(ByVal source As Object, ByVal e
As System.Web.UI.WebControls.DataGridPageChangedEventArgs) Handles
DataGrid1.PageIndexChanged
DataGrid1.CurrentPageIndex = e.NewPageIndex
Call BindGrid() ' bind data to the datagrid
End Sub

'code that the error is occurring in when page changed
'contains code for buttons inside template columns in datagrid
'in the .aspx file the datagrid's OnItemCommand property
'is set to reference this sub:
' OnItemCommand="ExecuteDataGridCommands"
Public Sub ExecuteDataGridCommands(ByVal sender As Object, ByVal e As
DataGridCommandEventArgs)

'reference textbox "txtID" inside current row of datagrid
Dim txtID As TextBox

'the following line is where the error occurs:
txtID = DataGrid1.Items(e.Item.ItemIndex).FindControl("txtID")

' i tried this instead, a paging error doesnt occur,
' but this line causes a different error (control not found):
' txtID = DataGrid1.FindControl("txtID")

'someone suggested this method, but it didn't work
'Dim iIndex As Int32
'iIndex = e.Item.ItemIndex - (DataGrid1.CurrentPageIndex *
DataGrid1.PageSize)
'txtID = DataGrid1.Items(iIndex).FindControl("txtID")

etc.
 
M

Mad Scientist Jr

I figured it out...

Evidently the datagrid template columns code is evaluated when a change
page event happens, and at the moment it is evaluated, the current
datagrid item is -1. Simply putting in a check for -1 solved the
probrem:

Public Sub ExecuteDataGridCommands(ByVal sender As Object, ByVal e
As DataGridCommandEventArgs)
If e.Item.ItemIndex > -1 Then
Dim txtID As TextBox
txtID =
DataGrid1.Items(e.Item.ItemIndex).FindControl("txtID")
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top