如何获取datagridview的所有行并将它们放入文本框中

时间:2015-11-07 05:36:11

标签: vb.net

是否可以获取datagridview的所有行并将它们放入文本框中?  (只有6行)。

我希望在将行加载到datagridview中的同时将行放入texbox中,而不选择任何当前行索引或选择多行索引。

需要帮助!

1 个答案:

答案 0 :(得分:0)

以下DataGridView在IDE中定义了六列。有三个TextBox,名为TextBox1,TextBox2,TextBox3。 TextBoxes上的键是有一个序数,所以我们可以将DataGridView中的行与TextBoxes匹配。另一个想法是动态创建TextBoxes,但这会带来游戏,房地产,所以在这种情况下也要考虑。

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        DataGridView1.Rows.Add(New Object() {"A1", "B1", "C1", "D1", "E1", "F1"})
        DataGridView1.Rows.Add(New Object() {"A2", "B2", "C2", "D2", "E2", "F2"})
        DataGridView1.Rows.Add(New Object() {"A3", "B3", "C3", "D3", "E3", "F3"})


        Dim Data As String() = DataGridViewRowsToStringArray(DataGridView1)
        If Data.Count <= DataGridView1.Rows.Count Then
            Dim items As Control() = Nothing
            For row As Integer = 0 To Data.Count - 1
                ' Find a TextBox as each textbox is named
                ' TextBoxn where n is a number e.g. TextBox1, TextBox2 etc.
                items = Me.Controls.Find("TextBox" & row + 1, False)
                If items IsNot Nothing Then
                    CType(items.FirstOrDefault, TextBox).Text = Data(row)
                End If
            Next
        End If
    End Sub
    Public Function DataGridViewRowsToStringArray(ByVal sender As DataGridView) As String()

        Dim RowData =
            (
                From row In sender.Rows
                Where Not DirectCast(row, DataGridViewRow).IsNewRow
                Let RowItem = String.Join(",",
                    Array.ConvertAll(
                       (
                       From X In DirectCast(row, DataGridViewRow).Cells.Cast(Of DataGridViewCell).ToArray
                       ).ToArray,
                                          Function(c As DataGridViewCell) _
                                              If(c.Value Is Nothing, "", c.Value.ToString)))
                Select RowItem).ToArray

        Return RowData

    End Function

End Class