Click here to Skip to main content
15,905,144 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
*** plzzz i dont want to use SqlDataAdapter or data set*******



i want to bind the data of SqlDataReader to the DataGrid but there is problem

.in that case only one record is displaying which is the last record of table.
C#
{
            con.Open();
            cmd =new SqlCommandd("SELECT * FROM student",con);
            rd= cmd.ExecuteReader();

            student stud=new student();
            ArrayList list = new ArrayList();

            while (rd.Read())
            {
                stud.roll = (int)rd[0];
                stud.name = (string) rd[1];
                stud.lname =(string) rd[2];

                list.Add(stud);
               dataGridView1.DataSource = list;
            }
            
            con.Close();
        }


if i am puting that " dataGridView1.DataSource = list;" out side of while loop it dispaly same last record several time .

*** plzzz i dont want to use SqlDataAdapter or data set*******
Posted
Updated 14-Jan-14 18:47pm
v2

Try like this..

C#
while (rd.Read())
           {
            var   stud  = new Student();
               stud.roll = (int)rd[0];
               stud.name = (string) rd[1];
               stud.lname =(string) rd[2];

               list.Add(stud);
             
           }

 dataGridView1.DataSource = list;
 
Share this answer
 
Comments
siddharth629 15-Jan-14 1:11am    
sir thanks ,

sir can you provide some link or guide line to understand my fault.
Karthik_Mahalingam 15-Jan-14 1:17am    
see siddharth,
what you have done is , stud object (single) is created outside..
you are keep on over writing the object properties in the while loop, so off course it will be over written with the last value only..

now what i have mentioned is
creating a new instance in the while loop , so that the new object with new properties will be stored in the object and in the collection..
Got it???
 
Share this answer
 
Comments
siddharth629 15-Jan-14 0:56am    
thanks.
Gitanjali Singh 15-Jan-14 0:59am    
welcome :)

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