我正在使用sqlite处理C#桌面应用程序。正确存储图像路径
喜欢C:\Users\USER\Pictures\pms_1484911839.45213251.jpg
。
我想在datagridview中显示图像。我的代码
private void loadTable(){
conn.Open();
SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter("SELECT * FROM products", conn);
DataTable dt = new DataTable();
dataAdapter.Fill(dt);
foodListView.AutoGenerateColumns = false;
foodListView.AllowUserToAddRows = false;
foodListView.RowHeadersVisible = false;
foodListView.DataSource = dt;
DataGridViewImageColumn imageColumn = new DataGridViewImageColumn();
Image img;
int i = 0;
imageColumn.HeaderText = "Image";
imageColumn.Name = "image";
foodListView.Columns.Insert(3, imageColumn);
foreach (DataRow dr in dt.Rows)
{
img = Image.FromFile(@dr["image"].ToString());
foodListView.Rows[i].Cells["image"].Value = img;
i++;
}
conn.Close();}
我的输出就像
我的问题在哪里。谢谢。
答案 0 :(得分:1)
//foreach (DataRow dr in dt.Rows)
//{
// img = Image.FromFile(@dr["image"].ToString());
// foodListView.Rows[i].Cells["image"].Value = img;
// i++;
//}
foodListView.CellFormatting += foodListView_CellFormatting;
private void foodListView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (foodListView.Columns[e.ColumnIndex].Name == "image")
{
e.Value = Bitmap.FromFile(e.Value.ToString());
e.FormattingApplied = true;
}
}
尝试应用cellformatting。确保列映射到相应的字段。
答案 1 :(得分:0)
如果要将文件中的图像加载到DataGridView
(在您的情况下,文件的路径在数据库中),那么这里是一个示例代码:
Bitmap img;
img = new Bitmap(dr[3].ToString); ////change column index as required
DataGridViewImageColumn imageColumn = new DataGridViewImageColumn();
////other codes here
dgv.Rows[0].Cells[3].Value = img;
希望这会有所帮助:)
答案 2 :(得分:0)