Gridview RowUpdating Error - Index was out of range
When I click the "Update" button in the gridview, it fire the RowUpdating event, but it returns a error "Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index"
The following is the vb code:
Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
If e.RowIndex >= 0 Then
Dim row As GridViewRow = DirectCast(Gridview1.Rows(e.RowIndex), GridViewRow)
Dim Col1_SL As CheckBox = DirectCast(row.FindControl("cb1_SL"), CheckBox)
.................
Dim cmd As New System.Data.SqlClient.SqlCommand
Dim sql As String
Dim reader As System.Data.SqlClient.SqlDataReader
Using conn As New System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("hris_shiftdutyConnectionString").ConnectionString)
conn.Open()
cmd.Connection = conn
sql = "SET DATEFORMAT dmy;UPDATE troster SET SL='" & Convert.ToInt32(Col1_SL.Checked) & "' where roster_key='" & Col1_RosterKey.Text & "';"
cmd.CommandText = sql
reader = cmd.ExecuteReader()
conn.Close()
reader.Close()
End Using
'Reset the edit index.
Gridview1.EditIndex = -1
'Bind data to the GridView control.
BindD开发者_开发问答ata()
End If
End Sub
Please help. Thanks Joe
Since the ViewState is disabled and you are only databinding when the page is not being posted back, this line is always going to fail:
Dim row As GridViewRow = DirectCast(Gridview1.Rows(e.RowIndex), GridViewRow)
as the count on Gridview1.Rows
is going to be 0.
When the page is posted back to the server, ASP.NET needs the ViewState to be enabled for the control so it can recreate the controls and properly determine which events to raise, which control values have changed, etc. You should enable the ViewState, and you'll have to figure out what is causing the control tree error. There must be some other modification that is taking place in the code.
Keep in mind that only databinding the GridView in Page_Load when the page is not posted back is correct, but you won't be able to properly handle events unless you enable ViewState on the control.
精彩评论