Sqlite在列表视图中填充项目

时间:2017-03-19 14:53:43

标签: c# android sqlite xamarin xamarin.android

我正在使用此代码创建新的SQL数据库并存储我的项目。

我用这段代码创建了一个类:

   class Contact
{
    public string Name { get; set; }

    public Contact(string name)
    {
        Name = name;
    }

    public Contact()
    {

    }

然后在我的主要活动中

         string dbPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "dbTest.db3");
    private List<string> mitems;
    private ListView mlistview;
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        SetContentView(Resource.Layout.Main);

      Button InsertAndShow = FindViewById<Button>(Resource.Id.button2);
        InsertAndShow.Click += delegate
        {
            EditText text = FindViewById<EditText>(Resource.Id.editext1);

            var db = new SQLiteConnection(dbPath);
            Contact mycontact = new Contact(text.Text);
            db.Insert(mycontact);
            var table = db.Table<Contact>();
            foreach (var item in table)
            {


                mlistview = FindViewById<ListView>(Resource.Id.listView1);
                mitems = new List<string>();

                mitems.Add(Convert.ToString(item.Name));

                ArrayAdapter<string> adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, mitems);

                mlistview.Adapter = adapter;

            }
        };

但它没有显示我的所有项目。它只显示最后一项。

1 个答案:

答案 0 :(得分:0)

mitems = new List<string>();

foreach (var item in table)
{
  mitems.Add(Convert.ToString(item.Name));
}

mlistview = FindViewById<ListView>(Resource.Id.listView1);
ArrayAdapter<string> adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, mitems);
mlistview.Adapter = adapter;