Asp.net 索引超出范围。必须为非负数且小于集合的大小

Asp.net 索引超出范围。必须为非负数且小于集合的大小,asp.net,vb.net,Asp.net,Vb.net,我有RowDatabound事件,我想在其中更改列名,如下所示: Protected Sub gvKeyValueOfstringstring_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvKeyValueOfstringstring.RowDataBound If e.Row.RowType = DataControlRowType.H

我有RowDatabound事件,我想在其中更改列名,如下所示:

 Protected Sub gvKeyValueOfstringstring_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvKeyValueOfstringstring.RowDataBound
        If e.Row.RowType = DataControlRowType.Header Then

            gvKeyValueOfstringstring.Columns(0).HeaderText = "Match"
            gvKeyValueOfstringstring.Columns(1).HeaderText = "Replace"
        End If
    End Sub
但我犯了一个错误:

索引超出范围。必须为非负数且小于集合的大小。
参数名称:index

可能
gvKeyValueOfstringstring。列的长度小于2,因此当您访问索引为0或1的列时,它将失败

在执行该代码之前,请检查是否已成功创建列

另外,我认为您不需要在RowDataBound事件中执行该命令,它可以在
Page\u Load
中执行(因此,如果它是标题,您不必检查每一行)。如果您想在那里执行此操作,可能只需更改该行单元格的值:

e.Row.Cells(0).Text = "Match"
e.Row.Cells(1).Text = "Replace"

无论如何,如果没有正确创建列,我希望此代码也会失败。

检查gridview
gvKeyValueOfstringstring
有多少列?一个简单的调试可以给出答案。列是自动生成的。gridview与有两列的xml绑定,这可能就是原因。尝试第二个选项,仅更改标题行的单元格文本第二个选项是什么。如何做到这一点?<代码> E.Rea.单元(0)。文本=“匹配”<代码>代码> E.Re.Cyter(1)。text =“替换”< /代码>您考虑解释该代码的任何机会,以及为什么它是对提出的问题的回答?
Private Sub BttnCan_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BttnCan.Click
        Dim val1 As Integer
        Try
            con.Open()
            For i As Integer = 0 To DataGridView1.Rows.Count
                val1 = Me.DataGridView1.Rows(i).Cells(2).Value

                com.CommandText = "INSERT INTO TblStock (Quant) VALUES (" & val1 & ")"

            Next

            con.Close()
        Catch ex As Exception
            MsgBox(Err.Description, MsgBoxStyle.Critical)
        End Try
    End Sub