How to assign a List<> to a Datatable correctly windowns Form?

Asked

Viewed 173 times

1

I’m trying to list the payment methods of the table dbo.FormaPgto in a Combobox but you’re making that mistake.

inserir a descrição da imagem aqui

Follows code.

Class:

 public List<Formas_Pagamento> ListarFormaPgto(string campos = "*")
        {
            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;

            }
        }

1 answer

1


To convert Datatable to a list you must 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);
}

Browser other questions tagged

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