我正在尝试向表中添加新行,第一行和第二行正常添加,但添加第三行时出现此错误:
指定的参数超出了有效值的范围 在这行代码中
Table1.Rows.Add(session_table.Rows(i))
我在第一个循环中追踪行计数,在添加行后行数变为2.我不明白为什么行数减少了?
我的代码如下
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim R As New TableRow
Dim C(4) As TableCell
C(0) = New TableCell
C(1) = New TableCell
C(2) = New TableCell
C(3) = New TableCell
C(4) = New TableCell
C(0).Text = martyr_name.Text
C(1).Text = link.Text
C(2).Text = martyr_type.Text
C(3).Text = dec_no.Text
C(4).Text = dec_date.Text
R.Cells.AddRange(C)
Table1.Rows.Add(R)
If Session("Table") Is Nothing Then
Session.Add("table", Table1)
Else
Session("table") = Table1
End If
End Sub
Private Sub form_Load(sender As Object, e As EventArgs) Handles Me.Load
If Session("table") IsNot Nothing Then
Dim session_table As New Table
session_table = Session("table")
For i = 1 To session_table.Rows.Count - 1
Table1.Rows.Add(session_table.Rows(i))
Next
End If
End Sub
答案 0 :(得分:0)
简而言之:零基指数。你需要从零位而不是一位循环,这就是你遇到IndexOutOfRangeException
的原因。
如果您不关心添加行的顺序,您可以始终使用ForEach
循环,这样可以减少对索引的处理。
Private Sub form_Load(sender As Object, e As EventArgs) Handles Me.Load
If Session("table") IsNot Nothing Then
Dim session_table As New Table
session_table = Session("table")
For i = 0 To session_table.Rows.Count - 1
Table1.Rows.Add(session_table.Rows(i))
Next
End If
End Sub