【问题标题】:If checkbox Checked then add to datatable from Gridview如果选中复选框,则从 Gridview 添加到数据表
【发布时间】:2016-08-31 20:40:57
【问题描述】:

我正在尝试检查是否在网格视图中选中了一个复选框,以及是否选中它以将其添加到数据表中。

但是,当未选中该行的复选框时,我收到一个错误:

位置 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

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

【问题讨论】:

    标签: asp.net vb.net checkbox


    【解决方案1】:

    如果您想向 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。不要这样做,因为它只是隐藏了你的问题。

    【讨论】:

      猜你喜欢
      • 2018-03-27
      • 2016-09-04
      • 1970-01-01
      • 1970-01-01
      • 2020-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-31
      相关资源
      最近更新 更多