从html表c#填充gridview

时间:2016-12-18 19:09:41

标签: c# asp.net

我有html页面,其中有许多元素,其中一个是表。如何获取表中的值并将它们附加到网格视图我使用html agility asp.net c#

这是我的试用

HtmlNodeCollection tables = pag1.Html.SelectNodes("//table[@id='data']");

DataTable tb = new DataTable();
HtmlNodeCollection rows = tables[0].SelectNodes("tr");
for (int i = 0; i <= rows.Count - 1; i++)
{
    HtmlNodeCollection cols = rows[i].SelectNodes("td");
    if (cols != null)
    {
        for (int j = 0; j <= cols.Count - 1; j++)
        {
            tb.Columns.Add(cols[j].InnerText);

        }

    }
}
GridView1.DataSource = tb;
GridView1.DataBind();

这个表

<table cellspacing="0" cellpadding="3" rules="cols" id="page1">
    <tr>
        <th scope="col">h1</th>
        <th scope="col">h2</th>
        <th scope="col">h3 </th>
        <th scope="col"> h4</th>
        <th scope="col"> h5</th>
    </tr>
    <tr >
        <td><input type="button" value="edit" onclick="javascript:__doPostBack()" /></td>
        <td>value 1</td>
        <td>value 2 </td>
        <td>value 3</td>
        <td>value 4</td>
    </tr>
    <tr>
        <td><input type="button" value="edit" onclick="javascript:__doPostBack()" /></td>
        <td>value 1</td>
        <td>value 2 </td>
        <td>value 3</td>
        <td>value 4</td>
    </tr>
    <tr>
        <td><input type="button" value="edit" onclick="javascript:__doPostBack()" /></td>
        <td>value 1</td>
        <td>value 2 </td>
        <td>value 3</td>
        <td>value 4</td>
    </tr>
</table>

1 个答案:

答案 0 :(得分:1)

首先尝试添加列,然后填充表格。我的代码可能有编译问题,因为我没有使用HTMLAgility但它肯定会指导你。

HtmlNodeCollection tables = pag1.Html.SelectNodes("//table[@id='data']");

DataTable tb = new DataTable();
HtmlNodeCollection rows = tables[0].SelectNodes("tr");

// create the columns
HtmlNodeCollection cols = rows[0].SelectNodes("th");
if (cols != null)
{
    for (int j = 0; j <= cols.Count - 1; j++)
    {
        tb.Columns.Add(cols[j].InnerText);
    }
}

// Now fill the table
for (int i = 0; i <= rows.Count - 1; i++)
{
    var newRow = tb.NewRow();
    HtmlNodeCollection cols = rows[i].SelectNodes("td");
    if (cols != null)
    {
        for (int j = 0; j <= cols.Count - 1; j++)
        {
            newRow[j] = cols[j].InnerText;
        }

    }

    // add the row to table
    tb.Rows.Add(newRow);
}
GridView1.DataSource = tb;
GridView1.DataBind();