从DataGridView获取信息

时间:2013-06-25 12:46:42

标签: vb.net datagridview

我需要获取位于用户选择的行的datagrid视图中的每个单元格中的信息。我有选择行,我只需要帮助获取单元格中的信息。现在,当数据真的是一个字符串时,它只返回DataGridVewRow { Index=7}。这是我的功能

Private Function getCoordinates()
    Dim dt As New DataTable
    Dim dt2 As New DataTable
    'Dim r As DataRow
    Dim n As Integer = 0
    Dim selectedItems As DataGridViewSelectedRowCollection = dgv.SelectedRows
    dt = dgv.DataSource
    dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect
    dgv.MultiSelect = True
    Dim i = dgv.CurrentRow.Index




    dt2.Columns.Add("Position")
    Try

        If selectedItems Is Nothing Then
            For n = 0 To dt.Rows.Count - 1
                dt2.Rows.Add(n)
                dt2.Rows(n)("Position") = dt.Rows.Item(n)("Mouse Position")
            Next

        Else

            For Each selectedItem As DataGridViewRow In selectedItems


                dt2.Rows.Add(selectedItem)
                dt2.Rows(selectedItem.Index)("Position") = dt.Rows.Item(selectedItem.Index)("Mouse Position")

            Next
        End If

    Catch ex As Exception
        MsgBox("Error", MsgBoxStyle.Exclamation, "Error!")
    End Try


    Return dt2


End Function

1 个答案:

答案 0 :(得分:1)

您可以通过DataGridViewRow的Cells属性获取单元格的文本。以下示例将从每个选定行的第一个单元格中获取文本:

Dim strContents As String = String.Empty

For Each selectedItem As DataGridViewRow In selectedItems

     strContents += " First Cell's Text: " & selectedItem.Cells(0).Text

Next