How to assign a List to a DataTable correctly form windowns?

1

I'm trying to list the payment methods of the dbo.FormaPgto table in a ComboBox but it's giving this error.

Followthecode.

Class:

publicList<Formas_Pagamento>ListarFormaPgto(stringcampos="*")
        {
            try
            {
                List<SqlParameter> listaParam = new List<SqlParameter>();

                Formas_Pagamento objFormaPgto = new Formas_Pagamento();
                strSQL = new StringBuilder();

                strSQL.Append("SELECT " + campos + " FROM FormaPagto WHERE 1=1");
                    strSQL.Append(" AND FPEmpresa = @CodEmpresa");
                    listaParam.Add(new SqlParameter("@CodEmpresa", FPEmpresa));


                if (FPCodigo > 0)
                {
                    strSQL.Append(" AND FPCodigo = @FPCodigo");
                    listaParam.Add(new SqlParameter("@FPCodigo", FPCodigo));
                }

                if (!string.IsNullOrEmpty(FPDescricao))
                {
                    strSQL.Append(" AND FPDescricao LIKE @FPDescricao");
                    listaParam.Add(new SqlParameter("@FPDescricao", "%" + FPDescricao + "%"));
                }

                DataTable dtFP = SqlDAO.consultarSQL(strSQL, listaParam.ToArray());
                return dtFP.ToList<Formas_Pagamento>();
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}

Method:

 protected void CarregarDDLFormaPagto()
        {
            try
            {
                Formas_Pagamento objFP = new Formas_Pagamento();
                objFP.FPEmpresa = Metodos.empresa;
                List<Formas_Pagamento> listaFP = objFP.ListarFormaPgto();
                cbxFormaPgto.DataSource = listaFP;
                cbxFormaPgto.DisplayMember = "FPDescricao";
                cbxFormaPgto.ValueMember = "FPCodigo";
                cbxFormaPgto.Enabled = true;

            }
            catch (Exception ex)
            {
                throw ex;

            }
        }
    
asked by anonymous 27.11.2017 / 13:38

1 answer

1

To convert the Datatable to a list you should do the following:

using System.Linq;
...
List<DataRow> list = dt.AsEnumerable().ToList();

or

 IEnumerable<DataRow> sequence = dt.AsEnumerable();

To convert to your specific List:

private List<object> GetListByDataTable(DataTable dt)
{
    var reult = (from rw in dt.AsEnumerable()
                 select new
                 {   
                     // Seus objetos aqui e as colunas do seu Dt
                     Name = Convert.ToString(rw["Name"]),
                     ID = Convert.ToInt32(rw["ID"])
                 }).ToList();

    return reult.ConvertAll<object>(o => (object)o);
}
    
27.11.2017 / 13:42