如何添加datagridview行

时间:2019-04-15 02:04:32

标签: vb.net datagridview

我收到此错误,“索引超出范围。必须为非负数且小于集合的大小。”我认为原因是因为我没有一行,而是在其中放置了一个值。

这是正确的吗?

DataGridView2.Rows.Add(New String() {0})

基本上,我正在对一组数据进行分组并将其复制到另一个表中。

For j As Integer = 1 To 29 Step 1
    Dim DGV2Max1 As New DataGridViewTextBoxColumn
    DGV2Max1.DataPropertyName = "Max" & j
    DGV2Max1.HeaderText = "Max" & j
    DGV2Max1.Name = "Max" & j
    DataGridView2.Columns.Add(DGV2Max1)
Next

For j As Integer = 1 To 29 Step 1
    For i As Integer = 0 To DataGridView1.RowCount - 1 Step 1
        If DataGridView1.Rows(i).Cells("Group").Value = j Then
         DataGridView2.Rows.Add(New String() {0})
         DataGridView2.Rows(i).Cells("Max" & j).Value = DataGridView1.Rows(i).Cells("Group").Value
        End If
    Next
Next

2 个答案:

答案 0 :(得分:0)

您正在尝试通过i访问每个DataGridView中相同编号的行。如果每次迭代都没有向DataGridView2添加一行,则此方法将无效。

与其尝试在每一行中使用同一行,不如在DataGridView2中找到最后一行并使用该行:

For j As Integer = 1 To 29 Step 1
    For i As Integer = 0 To DataGridView1.RowCount - 1 Step 1
        If DataGridView1.Rows(i).Cells("Group").Value = j Then
            DataGridView2.Rows.Add(New String() {0})
            DataGridView2.Rows(DataGridView2.Rows.Count - 1).Cells("Max" & j).Value = DataGridView1.Rows(i).Cells("Group").Value
        End If
    Next
Next

答案 1 :(得分:0)

这是我的最终代码

 Dim dgv2 As Integer = 0
    For j As Integer = 1 To 29 Step 1
        For i As Integer = 0 To DataGridView1.RowCount - 1 Step 1
            If DataGridView1.Rows(i).Cells("Group").Value = j Then
                DataGridView2.Rows.Add(New String() {0})
                DataGridView2.Rows(dgv2).Cells("Max" & j).Value = DataGridView1.Rows(i).Cells("X_Pitch").Value
                dgv2 += 1
            End If
        Next
    Next