自定义ListView从Sql添加数据

时间:2016-07-30 09:45:56

标签: android xamarin

您好我已创建自定义列表视图。现在我想在每个项目中添加sql中的数据。我在mainactivity中的原始代码是:

mlistview = FindViewById<ListView>(Resource.Id.myListView);
mItems = new List<Person>();
mItems.Add(new Person() { FirstName = "Dim", LastName = "Chris", Age = "25", Gender = "Male" });

MyListViewAdapter adapter = new MyListViewAdapter(this, mItems);
mlistview.Adapter = adapter;

现在我想从sql中添加我的每个项目数据。我尝试这样的事情:

mlistview = FindViewById<ListView>(Resource.Id.myListView);


SqlCommand sqlCmd = new SqlCommand("SELECT Name,LastName,Age,Gender FROM Members", con);
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.Read())
{     


mItems = new List<Person>();
mItems.Add(new Person() { FirstName = sqlReader["Name"].ToString(), LastName = sqlReader["LastName"].ToString(), Age = sqlReader["Age"].ToString(), Gender = sqlReader["Gender"].ToString() });

MyListViewAdapter adapter = new MyListViewAdapter(this, mItems);
mlistview.Adapter = adapter;
}
sqlReader.Close();

我只能看到我最后一个Sql行。但我希望看到我所有的SQL行。

1 个答案:

答案 0 :(得分:0)

您正在为查询中的每个行创建MyListViewAdapter的实例。每个ListView只需要一个Adapter实例。

所以,替换这个

while (sqlReader.Read())
{     
    mItems = new List<Person>();
    mItems.Add(new Person() { FirstName = sqlReader["Name"].ToString(), LastName = sqlReader["LastName"].ToString(), Age = sqlReader["Age"].ToString(), Gender = sqlReader["Gender"].ToString() });

    MyListViewAdapter adapter = new MyListViewAdapter(this, mItems);
    mlistview.Adapter = adapter;
}

// List of persons
mItems = new List<Person>();

// Add persons from the query to our list
while (sqlReader.Read())
{     
    mItems.Add(new Person() { FirstName = sqlReader["Name"].ToString(), LastName = sqlReader["LastName"].ToString(), Age = sqlReader["Age"].ToString(), Gender = sqlReader["Gender"].ToString() });
}

// Create an adapter for this list
MyListViewAdapter adapter = new MyListViewAdapter(this, mItems);

// Bind the ListView to this adapter
mlistview.Adapter = adapter;