将单元格的值从DataGridView列复制到ArrayList

时间:2015-01-24 23:25:08

标签: vb.net arraylist datagridview

我正在使用带有ArrayList的DataGridView。当用户单击一个按钮时,我想要将DataGridView的第一列(总共有4列,每个都有自己的ArrayList)的值写入ArrayList。我使用的是ArrayList,因为Datagridview中的行数可能会有所不同,因此数组大小不能是静态的。我编写的代码,实际搜索并在线获得帮助是“几乎”工作。它会将第一列的值写入arraylist,但我必须单击该按钮两次。它只会在第二次单击我的按钮时更新ArrayList。我的代码需要改变什么?感谢新手!

Private Sub btnPrintArray_Click(sender As Object, e As EventArgs) Handles btnPrintArray.Click

    Dim message = String.Join(Environment.NewLine, lftMtrAccelRates.ToArray())
    lftMtrAccelRates.Clear() 'clears ArrayList
    rchTxtBox.Clear() 'Clears rich text box that has array element values in it
    For Each d In LftMtr_Data_Grid.Rows.Cast(Of DataGridViewRow)()
        Dim num As Integer
        If Int32.TryParse(d.Cells(0).Value, num) Then
            lftMtrAccelRates.Add(num)
        End If
    Next
    rchTxtBox.Text = message
End Sub`

1 个答案:

答案 0 :(得分:0)

一种可能性:

Private values As New List(Of Integer)

Private Sub btnPrintArray_Click(sender As Object, e As EventArgs) Handles btnPrintArray.Click
    values.Clear()
    Dim num As Integer
    For Each d As DataGridViewRow In LftMtr_Data_Grid.Rows
        If Int32.TryParse(d.Cells(0).Value, num) Then
            values.Add(num)
        End If
    Next
    rchTxtBox.Lines = values.ConvertAll(Function(x) x.ToString).ToArray
End Sub