在代码中构建DataGridView显示(VB 2010 NET)

时间:2014-05-27 21:47:16

标签: vb.net winforms datagridview

我正在从Excel电子表格中提取信息并尝试在代码中构建DataGridView。我发现this information非常有帮助。在调试中,一切似乎都是正确的。我正确格式化了正确数量的列和行,但DataGridView上没有显示任何内容。为什么?这真是令人沮丧。

Dim dTable as New DataTable
For Each currcol As Excel.Range In inputRange.Columns
    dTable.Columns.Add(currcol.Value2, GetType(String))
Next

inputRange = objXLWs.Range("A" & HeaderRow + 1 & ":" & EndingColumn & EndingRow)
Dim i as Integer
For Each row As Excel.Range In inputRange.Rows
    Dim dataRow As DataRow = dTable.NewRow()
    i=0
    For Each incell As Excel.Range In row.Columns
        dataRow(i) = incell.Value2
        i += 1
    Next
    dTable.Rows.Add(dataRow)
Next

bs4DataPreview.DataSource = dTable         ' Set up BindingSource
dgv4PreviewData.AutoGenerateColumns = False
dgv4PreviewData.DataSource = bs4DataPreview
dgv4PreviewData.Show()
dgv4PreviewData.Refresh()

编辑源代码以反映DataTable的使用。 DataGridView上仍然没有任何结果。

1 个答案:

答案 0 :(得分:0)

这个问题最初提出已经有很长一段时间了。我继续研究这个问题,最后提出了一个有效的解决方案。它需要在DataTable中构建更多智能。

Dim inputRange As Excel.Range
Dim i As Integer

BuildPreview = False
EndingColumn = ColumnIndexToColumnLetter(EndingColumnNo)
EndingRow = objXLWs.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row

inputRange = objXLWs.Range("A" & HeaderRow & ":" & EndingColumn & HeaderRow)
i = 1
For Each currcol As Excel.Range In inputRange.Columns
    Dim column As New DataColumn

    column.DataType = GetType(String)
    column.ColumnName = "Column" & i.ToString
    column.Caption = NS(currcol.Value2)
    dTable.Columns.Add(column)
    i += 1
Next

inputRange = objXLWs.Range("A" & HeaderRow + 1 & ":" & EndingColumn & Math.Min(EndingRow, HeaderRow + previewRows))
For Each row As Excel.Range In inputRange.Rows
    Dim dataRow As DataRow = dTable.NewRow()
    i = 1
    For Each incell As Excel.Range In row.Columns
        dataRow("Column" & i.ToString) = NS(incell.Value2)
        i += 1
    Next
    dTable.Rows.Add(dataRow)
Next

我希望这证明对别人有帮助。