滚动时将数据库中的项目添加到Xamarin ListView

时间:2018-08-21 08:33:54

标签: c# sql database xamarin

我想在滚动的同时用数据库表中的数据填充ListView(从数据库中获取10条记录,当我到达ListView的末尾时-将数据库中的下10条记录添加到其中)。

这是我的代码,但是它以非常奇怪的方式工作:在开始时,ListView显示10条记录,然后向下滚动到末尾,它显示20条记录,然后显示40条记录,以此类推(似乎有很多记录加倍)。

我还有一个关于SQL的问题:如何在每个新查询中从DB获取下一个新的10条记录?

public class User
{
        public int userId { get; set; }
        public string userName { get; set; }
        public string userSurname { get; set; }
}

public partial class Users : ContentPage
{
        Project.Initial.Database DB = new Project.Initial.Database();
        DataTable usersDataTable = new DataTable();
        ObservableCollection<User> users = new ObservableCollection<User>();
        string queryText;
        bool isLoading;

        public Users()
        {
            InitializeComponent();

            ShowUsers();

            UsersList.ItemAppearing += (sender, e) =>
            {
                if (isLoading || users.Count == 0)
                    return;

                if (e.Item == users[users.Count - 1])
                {
                    ShowUsers();
                }
            };
        }

        void ShowUsers()
        {
            isLoading = true;

            // I don't know yet how to get next new 10 records from the table on every SQL query
            queryText = "SELECT * " +
                         "FROM users_test " +
                         "ORDER BY surname " +
                         "LIMIT 10";

            GetUsersFromDB();
        }

        void GetUsersFromDB()
        {
            DB.connection.Open();

            NpgsqlCommand command = new NpgsqlCommand(queryText, DB.connection);
            NpgsqlDataAdapter iAdapter = new NpgsqlDataAdapter(command);
            iAdapter.Fill(usersDataTable);

            DB.connection.Close();

            SaveUsersToList();
        }

        void SaveUsersToList()
        {
            Device.StartTimer(TimeSpan.FromSeconds(1), () =>
            {

                foreach (DataRow row in usersDataTable.Rows)
                {
                    users.Add(new User()
                    {
                        userId = Convert.ToInt32(row["id"]),
                        userName = row["name"].ToString(),
                        userSurname = row["surname"].ToString(),
                    });
                }

                isLoading = false;

                return false;
            });

            UsersList.ItemsSource = users;
        }
}

更新:

之前添加了users.Clear();
foreach (DataRow row in usersDataTable.Rows) 

更新2:

我认为它应该起作用

queryText = "SELECT * " +
            "FROM users_test " +
            "ORDER BY surname " +
            "LIMIT 10 " +
            "OFFSET " + 10;

但是当我从数据库获得所有行时如何停止呢?

UsersList.ItemAppearing += (sender, e) =>

0 个答案:

没有答案