Click here to Skip to main content
15,887,875 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
i want to copy all my data from database to generic list to which i will bind to gridview. but i won't be able to do it . what i am doing is as :
XML
public List<string>   fillgridviewDAL()
       {
           SqlConnection connection = new SqlConnection(constr);
           connection.Open();
                       command = new SqlCommand("spuserdetailsinfo", connection);  //******Don't fix the STORED PROCEDURE NAME in DAL. you have to pass it from BL.Remember that companies doesn't modify the DAL. They only play with .cs and BAL.
               command.CommandType = CommandType.StoredProcedure;
               dataset = new DataSet();
               dataadapter = new SqlDataAdapter();
               dataadapter.SelectCommand = command;
               dataadapter.Fill(dataset);
               connection.Close();
               connection.Dispose();


               List<string> NameList = (from r in dataset.Tables["MyTableName"].AsEnumerable()
                                        select r.Field<string>("name")+ r.Field<string>("age")+r.Field<string>("salary")+r.Field<string>("city")).ToList();
               return NameList;
       }

when i see contents in dataset it shows full table but when i use generic list using above method it concat columns and gives a resultant row at particular index. In short it gives me output in int form. than how can i bind the gridview to my generic list...Thanking u all.
Posted
Updated 8-Aug-13 2:50am
v2

1 solution

It gives you a concatenated output because that's what you are asking it to do.
Instead of concatenating the columns, project columns in a new anonymous type.
Change your code as below:
C#
var NameList = (from r in dataset.Tables["MyTableName"].AsEnumerable()
                            select new
                            {
                                Name = r.Field<string>("name"),
                                Age = r.Field<string>("age"),
                                Salary = r.Field<string>("salary"),
                                City = r.Field<string>("city")
                            });


This basically creates an anonymous type which is a collection having columns Name, Age, Salary and City. You can iterate through them using a foreach loop. Also remember that the query will execute only when the result collection will be iterated. Add ToList() in the end if you want to execute it at that very moment.

You GridView should accept anonymous type as DataSource. Just take care of the column names.

Hope that helps!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900