我目前正在转换一些将数据存储在XML文件中的代码,而不是将其存储在SQLite数据库中。该数据库有一个包含4列的表:
thumbnail | title | threadid | url
数据库中的所有条目都是字符串。使用旧代码,我从XML文件中提取所有数据,并使用值填充数据网格。我的目标是这样做,但使用从SQLite数据库中提取的数据。我可以成功地从数据库表中提取所有数据,如下所示:
public List<Database> getFromTable()
{
List<Database> items = new List<Database>();
string sql = "SELECT * FROM blacklist";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
using (SQLiteDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
var item = new Database();
item.imgstring = (string)reader["thumbnail"];
item.titlestring = (string)reader["title"];
item.threadidstring = (string)reader["threadid"];
item.urlstring = (string)reader["url"];
items.Add(item);
}
}
return items;
}
我现在坚持的部分是如何使用列表中返回的结果。目前我正在调用这样的方法:
var items = database.getFromTable();
然而,在找不到一些示例后,我无法弄清楚如何将foreach
行放在一起使用返回列表中的项目。例如;
foreach (??? in items)
{
// Populate line in datagrid with thumbnail, title, threadid, url
}
我可以填充数据网格,它只是理解如何将我的“项目”分解为可用的表单。任何指针赞赏。
编辑我将把这些信息添加到数据网格中,这样SQLite表中的每个单元格值都会被添加到数据网格上的匹配单元格中。
编辑2 值得一提的是,虽然我的SQLite数据库中的thumbnail
是一个字符串值,但它实际上是一个已转换为Base64ImageRepresentation
的图像,因此我可以存储它作为字符串值。从SQLite数据库获取每个值的一部分是,我可以在添加到我的DataGridView
之前将此字符串转换回图像。
答案 0 :(得分:1)
放弃自定义对象会更容易,而只需阅读DataTable
并直接将其用作DataGridView
的来源。
如果必须使用自定义对象,则必须循环遍历它们,从网格的数据源创建行,然后逐行填充行,并在填充后再添加它们。
这样的事情:
foreach (var item in getFromTable())
{
var index = grid.Rows.Add();
var row = grid.Rows[index];
row.SetValues(item.imgstring, item.titlestring, item.threadidstring, item.urlstring); //order of the items must match field order in grid
}
不过,我会选择绑定到可靠的数据源。但这应该给你一般的想法。