简体   繁体   English

Xamarin.Forms中的Sqldatareader-填充ListView

[英]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 . 我正在尝试在Xamarin.Forms中填充我的ListView I do this by MySqlDataReader. 我通过My​​SqlDataReader做到这一点。 With this code I get only one record from database because the while loop is overriding it. 使用这段代码,我从数据库中仅获得一条记录,因为while循环覆盖了它。

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: instructors声明放在while循环之外:

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. 当前,您正在覆盖您的集合,而不是在每次循环迭代时向您的集合添加新的讲师。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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