【问题标题】:HTML Table Code To DatagridviewHTML表格代码到Datagridview
【发布时间】:2016-05-16 06:00:32
【问题描述】:

我的 VB.NET 应用程序中有 HTML 表格代码。我想通过 DataGridView 显示表格。我曾尝试使用 for next 但我不太了解它。有没有其他方法可以做到这一点?

【问题讨论】:

  • 如果您只需要显示它,您可以使用 Webbrowser 而不是 DataGridView

标签: vb.net


【解决方案1】:

如果 WebBrowser 不适合此,我建议使用 HTML Agility Pack。这是一个非常简单的例子。

为了这个演示,我在项目属性下创建了一个资源,资源添加了新的文本文件并将其命名为 MyHtml,将以下内容转储到其中。

<!DOCTYPE html>
<head>
    <title></title>
</head>
<body>
    <table border="1" bordercolor="#808080" cellpadding="2">
        <tr>
            <th>One</th>
            <th>Two</th>
            <th>Three</th>
        </tr>
        <tr>
            <td>Row 1 A</td>
            <td>Row 1 B</td>
            <td>Row 1 C</td>
        </tr>
        <tr>
            <td>Row 2 A</td>
            <td>Row 2 B</td>
            <td>Row 2 C</td>
        </tr>
    </table>
</body>
</html>

给项目添加一个类

Public Class Class1
    Public Function Demo1() As DataTable
        Dim Document As New HtmlAgilityPack.HtmlDocument()

        Document.LoadHtml(My.Resources.MyHtml)
        Dim table As HtmlAgilityPack.HtmlNode =
            Document.DocumentNode.SelectSingleNode("//table[@border='1']")

        Dim dt As New DataTable()

        Dim rows = table.SelectNodes("tr")

        For row As Integer = 0 To rows.Count - 1
            'if row = then these are headers
            If row = 0 Then

                Dim cols = rows(row).SelectNodes("th")

                dt.Columns.Add(New DataColumn(cols(0).InnerText.ToString()))
                dt.Columns.Add(New DataColumn(cols(1).InnerText.ToString()))
                dt.Columns.Add(New DataColumn(cols(2).InnerText.ToString()))

            Else
                Dim cols = rows(row).SelectNodes("td")

                Dim dr As DataRow = dt.NewRow()

                dr(0) = cols(0).InnerText.ToString()
                dr(1) = cols(1).InnerText.ToString()
                dr(2) = cols(2).InnerText.ToString()

                dt.Rows.Add(dr)

            End If
        Next

        Return dt

    End Function
End Class

在表格中

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim c1 As New Class1
        dataGridView1.DataSource = c1.Demo1
    End Sub
End Class

【讨论】:

    猜你喜欢
    • 2016-03-13
    • 2011-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-18
    • 2017-03-17
    • 1970-01-01
    相关资源
    最近更新 更多