10

this is my code... but i need select only column to display in my Datagridview. I Need the code to select only some columns.. example

Select{t => t.usu_Login, t => t.usu_Login}

public List<tb_usuario> Get(FilterDefinition filter)
{

     var contexto = new indNET_Entities();

     IQueryable<tb_usuario> Consulta = contexto.tb_usuario.AsQueryable<tb_usuario>()
                                                        .Where(t => t.usu_Ativo == 1)
                                                        .OrderBy(t => t.usu_Login);


     return Consulta.ToList();

}
Daniel Mann
  • 57,011
  • 13
  • 100
  • 120
MrZerocaL
  • 103
  • 1
  • 1
  • 5

4 Answers4

12

If you only want a limited number of columns and you intend to pass the result out of the method, first declare a concrete type to describe the elements.

public class UsuarioData
{
     public string UsuLogin { get; set; } // or whatever
     public string UsuName { get; set; }  // or whatever
}

Then you can use this in the return type for the method

public List<UsuarioData> Get(...) 

And finally, use the type in your select.

var consulta = contexto.tb_usuario.Where(whatever).OrderBy(whatever)
                   .Select(t => new UsuarioData
                                {
                                     UsuLogin = t.usu_login,
                                     UsuName = t.usu_name
                                }
                           );

return consulta.ToList();

And, of course, your callers should expect to get this as the result (or just use type inference with var).

Anthony Pegram
  • 123,721
  • 27
  • 225
  • 246
  • i try this code but the select show me all fields in datagridview. http://img59.imageshack.us/img59/9585/aaaabw.jpg and i select only two fields.. sorry for my bad english ! – MrZerocaL Jan 20 '12 at 16:49
1

Well there is a few ways you could do this, the easiest way:

     grdvwHoldings.DataSource = Model.Holdings
                                .Select(x=> new 
                                            { Name= x.HoldingName, 
                                              CustomerName = x.FundCustomerName 
                                             }).ToList();
     grdvwHoldings.DataBind();

Alternatively you could create a class and substitute the new {} for the class and do it at the data layer level.

Nickz
  • 1,880
  • 17
  • 35
1
 IQueryable<tb_usuario> Consulta = contexto.tb_usuario.AsQueryable<tb_usuario>()
                                                    .Where(t => t.usu_Ativo == 1)
                                                    .OrderBy(t => t.usu_Login)
                                                    .Select(t => t.ColumnName);
1

Try this:

(contexto.AsEnumerable() 
select new {usu_Login=r.Field<string>("usu_Login")}).ToList();
Vinod
  • 4,672
  • 4
  • 19
  • 26