Import HTML to Datagridview [C#]

Asked

Viewed 53 times

2

I’m working for the first time with HtmlAgilityPack for reading an HTML file that I’m manipulating. The idea is to take certain data from this file and insert it into the respective columns of my datagridview.

The code I use to read and obtain each information, is this:

  string pagina = tb_SourceHTML.Text.Trim();

        var htmlDocument = new HtmlAgilityPack.HtmlDocument();
        htmlDocument.LoadHtml(pagina);

        string ClassToGet = "semBorda";


        DataTable dt = new DataTable();

        foreach (HtmlNode node in htmlDocument.DocumentNode.SelectNodes("//td[@class='" + ClassToGet + "']"))
        {
            string value = node.InnerText;
            dtgridview_ProdutosInventarioInicial.Rows.Add(value);   
        }

The HTML file that is read, is basically constituted in this way:

<td width="17%" class="semBorda" height="20">1.1213.0424.003-0</td>
        <td width="50%" class="semBorda" height="20">ALPRAZOLAM</td>
        <td width="18%" class="semBorda" height="20">1601792</td>
        <td width="15%" class="semBorda" height="20">2
</td>

 <td width="17%" class="semBorda" height="20">1.1213.0424.003-0</td>
        <td width="50%" class="semBorda" height="20">ALPRAZOLAM</td>
        <td width="18%" class="semBorda" height="20">1601792</td>
        <td width="15%" class="semBorda" height="20">2
</td>

  .
  .
  .

But the problem is in the insertion part.

Currently, the information stays this way after entering the data:

inserir a descrição da imagem aqui

However, I would like each, each information, from each tag of the <td> be inserted in the columns of my datagridview. (first <td>in the first column, second column <td> in the second column and so on).

In this way:

inserir a descrição da imagem aqui

I tried to insert in datagridview in this way:

string value = node.InnerText;
dtgridview_ProdutosInventarioInicial.Rows.Add(value, value, value);   

But records repeat instead of being inserted one at a time only once.

inserir a descrição da imagem aqui

  • it would be easier to make the Selectnodes by tr (Row), and then divide by cell (td)... when doing Rows.Add() already have to carry all the columns in the parameters... dtgridview_ProdutosInventarioInicial.Rows.Add(valor_da_coluna1, valor_da_coluna2);

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.