VB .NET - 将datagridview(datatable)值复制到数组时出错

时间:2017-06-09 10:30:15

标签: arrays vb.net datagridview datatable

我已经成功使用datatable创建了本地数据库,并且它已在datagridview中显示。但我想将值复制到数组中,以便我可以在其他代码中处理它。

例如

coba(0,0) = data in datagridviewResources column 0 row 0

coba(0,1) = data in datagridviewresources column 0 row 1

但是我得到了错误:

  

指数超出范围。必须是非负数且小于集合的大小。

我的代码:

Dim table As New DataTable("Table")
Dim index As Integer
Dim coba(100, 100) As String

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    table.Columns.Add("ID", Type.GetType("System.Int32"))
    table.Columns.Add("Filename", Type.GetType("System.String"))
    table.Columns.Add("Column", Type.GetType("System.Int32"))
    datagridviewResources.DataSource = table
End Sub

Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
    Dim newDataRow As DataGridViewRow
    newDataRow = datagridviewResources.Rows(index)
    newDataRow.Cells(0).Value = txtID.Text
    newDataRow.Cells(1).Value = txtFilename.Text
    newDataRow.Cells(2).Value = txtColumn.Text
End Sub

Private Sub datagridviewResources_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles datagridviewResources.CellClick
    index = e.RowIndex
    Dim selectedRow As DataGridViewRow
    selectedRow = datagridviewResources.Rows(index)
    txtID.Text = selectedRow.Cells(0).Value.ToString()
    txtFilename.Text = selectedRow.Cells(1).Value.ToString()
    txtColumn.Text = selectedRow.Cells(2).Value.ToString()
End Sub

Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
    datagridviewResources.Rows.RemoveAt(index)
End Sub

Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
    table.Rows.Add(txtID.Text, txtFilename.Text, txtColumn.Text)
    datagridviewResources.DataSource = table
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click, datagridviewResources.SelectionChanged
    For i = 0 To table.Rows.Count
        For j = 0 To table.Columns.Count
            coba(i,j) = datagridviewResources.Rows(i).Cells(j).Value.ToString())
        Next
    Next
End Sub

0 个答案:

没有答案