如果选中复选框,则从Gridview添加到数据表

时间:2016-08-31 20:40:58

标签: asp.net vb.net checkbox

我正在尝试检查是否在gridview中选中了复选框,是否选中它以将其添加到数据表中。

但是,当取消选中该行的复选框时,我收到错误:

  

位置1没有行。

这是我的代码:

       'Creates a new datatable
        Dim dtQuestions As New DataTable("QuestionsData")

        'Add columns to datatable
        For Each cell As TableCell In example.HeaderRow.Cells

            dtQuestions.Columns.Add(cell.Text)

        Next

        For Each row As GridViewRow In example.Rows

            Dim chkTest As CheckBox = CType(row.FindControl("chkTest"), CheckBox)
            If chkTest.Checked = True Then

                dtQuestions.Rows.Add()

                For i As Integer = 0 To row.Cells.Count - 1

                    Try

                        dtQuestions.Rows(row.RowIndex)(i) = row.Cells(i).Text

                    Catch ex As Exception

                    End Try


                Next

            Else

                'Do not add it to Datatable

            End If

        Next

我收到此代码的错误:

  

dtQuestions.Rows(row.RowIndex)(i)= row.Cells(i).Text

我不知道如何解决这个问题。

1 个答案:

答案 0 :(得分:0)

如果要向DataTable添加行,则应编写此代码

For Each row As GridViewRow In example.Rows
    Dim chkTest As CheckBox = CType(row.FindControl("chkTest"), CheckBox)
    If chkTest.Checked = True Then

        Dim tableRow = dtQuestions.NewRow()

        For i As Integer = 0 To row.Cells.Count - 1
           tableRow(i) = row.Cells(i).Text
        Next
        dtQuestions.Rows.Add(tableRow)
    End If
Next

请注意,我已删除了空的try / catch。不要这样做,因为它只是隐藏了你的问题。

相关问题