Xamarin.Forms中的Sqldatareader - 填充ListView

时间:2017-12-28 15:10:12

标签: c# android listview xamarin.forms

        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;
        }

嗨!

我正在尝试填写 Xamarin.Forms 中的 ListView 。我通过My​​SqlDataReader执行此操作。使用此代码,我只从数据库中获取一条记录,因为 while 循环覆盖了它。

当我想用数据库中的所有数据填充列表时,我该怎么做?

1 个答案:

答案 0 :(得分:0)

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;

目前,您正在覆盖您的集合,而不是在每次循环迭代时向您的集合添加新的教师。