简体   繁体   中英

Image display issue in datagridview from imagepath stored in database(sqlite) in windows form(C#)

I am working C# desktop application with sqlite. Store Image path properly as

like C:\\Users\\USER\\Pictures\\pms_1484911839.45213251.jpg .

And I want to display the images in datagridview. My Code

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();}

My Output is like

在此处输入图片说明

Where is my problem. Thank you.

//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;
        }
    }

try to apply cellformatting. make sure column is mapped with respective field.

If you want to load image from aa file into the DataGridView (in your case the path of the file is in the database) , then here's a sample code :

  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;

Hope this helps :)

Actually the code in the above working absolutely fine. But the problem was I call loadTable() before the form loaded. That's why the function creates image dispay issue. When I call the function after the form load images load properly. Thank you everyone.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM