Search This Blog

Monday 30 April 2012

De Gereric List para DataTable

Olá , Pessoal

Depois de um bom tempo sem postar nada volto eu , para falar sobre uma funcionalidade que achei super interessante , estou voltando a trabalhar com ASP webforms e algumas coisas que estou achando legal vou começar a compartilhar com vocês.

Como exemplo a maioria dos componentes do ASP webforms trabalhão com ADO.NET para persistência de dados , por conta disso temos as vezes , a necessidade de transformar uma lista do tipo LIST ou list generic em uma DataTable com exemplo que vou mostrar para vocês como popular um GridView com uma DataTable que tem como base de informações um LIST.

Exemplo:

Arquivo : DbTools.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.ComponentModel;

namespace aarvaniExample1
{
    public class DbTools
    {
        /// <summary>
        /// Método para conversão de uma lista tipo generic LIST<T> para DataTable
        /// </summary>
        /// <param name="data"> List<T></param>
        /// <returns>DataTable</returns>
        public static DataTable ConvertListToDataTable(List<Object> data)
        {
            //Pegar o primeiro registro e listar suas propriedades            
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(data.FirstOrDefault());
            //Criar e instanciar a tabela auxiliar em memória
            DataTable table = new DataTable();

            //Consultar item a item das propriedades
            foreach (PropertyDescriptor prop in properties)
                //Adicionar programaticamente a coluna com seus respectivos tipos
                table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);

            //Consultar coluna a coluna da tabela auxiliar
            foreach (Object item in data)
            {
                //Criar e instanciar a linha
                DataRow row = table.NewRow();

                //Consultar item a item das propriedades
                foreach (PropertyDescriptor prop in properties)
                    //Adicionar o valor da linha na coluna caso não seja nulo
                    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value; table.Rows.Add(row);
            }

            //Retornar a tabela
            return table;
        }
    }
}

Arquivo : Pedido.cs


namespace Entidade
{
 
    /// <summary>
    /// Classe pedido
    /// </summary>
    public class Pedido
    {

                       
        
        #region Propriedades

        public int      Numero { get; set; }        
        public int      ClienteCodigo { get; set; }
        public double   Valor { get; set; }
        public string   Prazo { get; set; }
        public decimal  Quantidade { get; set; }
        
        #endregion

        #region Listas

        public static List<Pedido>  Lista { get; set; }
               
        
        #endregion

    }
}

Arquivo : pedidos_lista.aspx

CODE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace aarvaniExample1
{
    public partial class pedidos_lista : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //Popular dados
           
            Entidade.Pedido ped = new Entidade.Pedido();
           
            ped.ClienteCodigo = 1;
            ped.Numero = 123;
            ped.Prazo = "30/60";
            ped.Quantidade = 1;
            ped.Valor = 1;
            Entidade.Pedido.Lista = new List<Entidade.Pedido>();
            Entidade.Pedido.Lista.Add(ped);

            List<object> List = new List<object>();
            List.AddRange(Entidade.Pedido.Lista);
           
            gvListaPedidos.DataSource = DbTools.ConvertListToDataTable(List);
            gvListaPedidos.DataBind();
        }

       
    }
}
SOURCE
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="pedidos_lista.aspx.cs" Inherits="aarvaniExample1.pedidos_lista" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="gvListaPedidos" AutoGenerateColumns="true" runat="server" />    
    </div>
    </form>
</body>
</html>

Segue link para baixar o codigo completo.

Download
Espero que gostem .

Até a próxima !

Translate