2016-05-16 42 views
0

我在我的VB.NET應用程序中有HTML表代碼。我想通過DataGridView顯示錶格。我曾嘗試使用下一個,但我不太瞭解它。有沒有另一種方法來做到這一點?HTML表代碼到Datagridview

+0

如果你只需要顯示它您可以使用一個網頁瀏覽器,而不是DataGridView的 – genespos

回答

0

如果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 

enter image description here