简体   繁体   中英

Sqldatareader in Xamarin.Forms - filling up the ListView

        MySqlConnection sqlconn = new MySqlConnection(MyConnectionString);


        sqlconn.Open();

        MySqlCommand sqlcmd1 = new MySqlCommand("SELECT * FROM Instructor", sqlconn);
        MySqlDataReader dr1;
        dr1 = sqlcmd1.ExecuteReader();



        while (dr1.Read())
        {

            // get the results of each column
            int id = (int)dr1["ID_Instructor"];
            string firstname = (string)dr1["f_name"];
            string lastname = (string)dr1["l_name"];
            string school = (string)dr1["d_school"];
            string category = (string)dr1["category"];

            var instructors = new List<Instructor>
        {
            new Instructor
            {
                Id = id,
                Fullname = firstname+" "+lastname,
                Details = school+" "+category

            }

         };

            InstructorsListView.ItemsSource = instructors;
        }

Hi!

I'm trying to fill up my ListView in Xamarin.Forms . I do this by MySqlDataReader. With this code I get only one record from database because the while loop is overriding it.

How should I do this when I want to fill the list with all of the data from database?

Put the instructors declaration outside of your while loop:

var instructors = new List<Instructor>();
while (dr1.Read())
{ 
  ..
  /* Populate here your instructor data */
  var instructor = new Instructor
  {
    Id = id,
    Fullname = firstname+" "+lastname,
    Details = school+" "+category
  }
  instructors.Add(instructor);
}
InstructorsListView.ItemsSource = instructors;

Currently you are overriding your collection instead of adding a new instructor to your collection on each loop iteration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM