简体   繁体   English

如何在dataGridView中显示图片?

[英]How to display images in dataGridView?

Description.描述。
It is supposed to store paths to images like *.ico , *.jpg , *.png in the database.它应该在数据库中存储*.ico*.jpg*.png等图像的路径。
Database types:数据库类型:

  • SQLlite;精简版;
  • SQLServer;数据库;
  • MySQL; MySQL;

I am using DataTable dt to simulate the result of a SELECT query.我正在使用DataTable dt来模拟SELECT查询的结果。

Question.题。

  1. How to display images in dataGridView?如何在dataGridView中显示图片?
  2. What is the most common practice for storing images in a database?在数据库中存储图像的最常见做法是什么? Store as paths or is it better to use other options?存储为路径还是使用其他选项更好?
  3. Are there any mistakes in the code?代码中有错误吗?

I am running the application.我正在运行应用程序。
Result: error.结果:错误。
Error:错误:
Exception in DataGridView: DataGridView 中的异常:
System.FormatException: Invalid cast "System.String" to "System.Drawing.Image". System.FormatException:将“System.String”强制转换为“System.Drawing.Image”无效。

Picture-1图片1
在此处输入图像描述

Code代码

public partial class Form1 : Form
{
    DataTable dt = new DataTable();
    string pathProject = AppDomain.CurrentDomain.BaseDirectory;

    public Form1()
    {
        InitializeComponent();

        dgv.CellFormatting += Dgv_CellFormatting;
    }

    private void Dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        if (dgv.Columns[e.ColumnIndex].Name == "IcoPath")
        {
            string fullpath = pathProject + e.Value.ToString();

            // e.Value = Bitmap.FromFile(fullpath);

            Image p_ImageIn = new Bitmap(fullpath);
            ImageConverter imgConverter = new ImageConverter();
            e.Value = (byte[])imgConverter.ConvertTo(p_ImageIn, typeof(Byte[]));
            e.FormattingApplied = true;
        }

    }

    private void button1_Click(object sender, EventArgs e)
    {
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("IcoPath", typeof(string));
        dt.Columns.Add("JpgPath", typeof(string));
        dt.Columns.Add("PngPath", typeof(string));


        // dt.Rows.Add("Name_1", @"Resources\Picture\ico\ico_1.ico");
        // dt.Rows.Add("Name_2", @"Resources\Picture\ico\ico_2.ico");
        // dt.Rows.Add("Name_3", @"Resources\Picture\ico\ico_3.ico");

        // dt.Rows.Add("Name_1", @"Resources\Picture\jpg\Jpg_1.jpg");
        // dt.Rows.Add("Name_2", @"Resources\Picture\jpg\Jpg_2.jpg");
        // dt.Rows.Add("Name_3", @"Resources\Picture\jpg\Jpg_3.jpg");

        // dt.Rows.Add("Name_1", @"\Resources\Picture\png\Png_1.png");
        // dt.Rows.Add("Name_2", @"\Resources\Picture\png\Png_2.png");
        // dt.Rows.Add("Name_3", @"\Resources\Picture\png\Png_3.png");

        dt.Rows.Add("Name_1", @"Resources\Picture\ico\ico_1.ico", @"Resources\Picture\jpg\Jpg_1.jpg", @"\Resources\Picture\png\Png_1.png");
        dt.Rows.Add("Name_2", @"Resources\Picture\ico\ico_2.ico", @"Resources\Picture\jpg\Jpg_2.jpg", @"\Resources\Picture\png\Png_2.png");
        dt.Rows.Add("Name_3", @"Resources\Picture\ico\ico_3.ico", @"Resources\Picture\jpg\Jpg_3.jpg", @"\Resources\Picture\png\Png_3.png");

        DataGridViewImageColumn icoColumn = new DataGridViewImageColumn();
        //icoColumn.HeaderText = "Image_Header";
        icoColumn.Name = "IcoPath_Name";
        icoColumn.DataPropertyName = "IcoPath";
        //// dgv.Columns.Insert(3, imageColumn);
        dgv.Columns.Add(icoColumn);

        DataGridViewImageColumn jpgColumn = new DataGridViewImageColumn();
        //icoColumn.HeaderText = "Image_Header";
        jpgColumn.Name = "JpgPath_Name";
        jpgColumn.DataPropertyName = "JpgPath";
        //// dgv.Columns.Insert(3, imageColumn);
        dgv.Columns.Add(jpgColumn);


        DataGridViewImageColumn pngColumn = new DataGridViewImageColumn();
        //icoColumn.HeaderText = "Image_Header";
        pngColumn.Name = "PngPath_Name";
        pngColumn.DataPropertyName = "PngPath";
        //// dgv.Columns.Insert(3, imageColumn);
        dgv.Columns.Add(pngColumn);


        dgv.DataSource = dt;
    }
}

Picture-2图2
在此处输入图像描述


Update-1更新-1

When creating a solution for this issue, please do not consider images as "embedded in the project".在为此问题创建解决方案时,请不要将图像视为“嵌入在项目中”。
Application logic:应用逻辑:

  • connect to the database;连接到数据库;
  • execute the request;执行请求;
  • query result: DataTable dt ;查询结果: DataTable dt ;
  • DataTable dt contains paths to images; DataTable dt包含图像的路径;

Basically, since the images are NOT coming from a DB but are embedded in the project as shown from the solution explorer picture, your code is going to have to “build” this DataTable using those embedded resources.基本上,由于图像不是来自数据库,而是嵌入到项目中,如解决方案资源管理器图片所示,您的代码将不得不使用这些嵌入资源“构建”此DataTable

Is what it appears you are trying to do is “add” the pictures to the grids “column.”看起来您正在尝试做的是将图片“添加”到网格“列”。 You want to add the images to the DataTable ROWS.您想要将图像添加到DataTable ROWS。 Then, it will be unnecessary to “add” the “grid image” column to the grid.那么,就不需要将“网格图像”列“添加”到网格中了。 The grid will know how to display the images from the DataTable since they are “actual” images.网格将知道如何显示来自DataTable的图像,因为它们是“实际”图像。

Below is a small example with only one image column, however it should not be difficult to add the other columns using the same strategy.下面是一个只有一个图像列的小例子,但是使用相同的策略添加其他列应该不难。 Also, I am getting the images that are embedded as a resource in the project as your current picture shows.此外,我正在获取作为资源嵌入到项目中的图像,如您当前的图片所示。 You will need to change the text that says “ProjectName” with the name of your project in addition to the image file names.除了图像文件名之外,您还需要用项目名称更改“ProjectName”的文本。

  DataTable dt = new DataTable();
  dt.Columns.Add("Name", typeof(string));
  dt.Columns.Add("JpgPath", typeof(Image));

  Assembly myAssembly = Assembly.GetExecutingAssembly();
  Stream myStream = myAssembly.GetManifestResourceStream("ProjectName.Resources.Picture.jpg.image1.jpg");
  Image jpg1 = new Bitmap(myStream);
  myStream = myAssembly.GetManifestResourceStream("ProjectName.Resources.Picture.jpg.image2.jpg");
  Image jpg2 = new Bitmap(myStream);
  myStream = myAssembly.GetManifestResourceStream("ProjectName.Resources.Picture.jpg.image3.jpg");
  Image jpg3 = new Bitmap(myStream);

  dt.Rows.Add("Name1", jpg1);
  dt.Rows.Add("Name2", jpg2);
  dt.Rows.Add("Name3", jpg3);

  dgv.DataSource = dt;

Edit from OP question.从 OP 问题编辑。

The example below shows two methods.下面的示例显示了两种方法。 The first is a simulation of getting the data from the DB where the images are not there but the string paths to the images are.第一个是从数据库中获取数据的模拟,其中图像不存在但图像的字符串路径存在。

Once we have the DataTable from the DB, we need to “add” those images to each row in the existing DataTable .从数据库中获得DataTable后,我们需要将这些图像“添加”到现有DataTable中的每一行。 Obviously, we need to “add” the new “Image” column to the existing DataTable we got from the DB.显然,我们需要将新的“图像”列“添加”到我们从数据库中获取的现有DataTable中。 Then loop through each row and add the image to the image column based on the path in that row.然后循环遍历每一行,并根据该行中的路径将图像添加到图像列。

private void Form1_Load(object sender, EventArgs e) {
  DataTable DBTable = GetTableFromDB();
  AddImageColumnToDT(DBTable);
  dgv.DataSource = DBTable;
}


private DataTable GetTableFromDB() {
  DataTable dt = new DataTable();
  dt.Columns.Add("Name", typeof(string));
  dt.Columns.Add("ImagePath", typeof(string));
  dt.Rows.Add("Name1", "PathTo_Image1");
  dt.Rows.Add("Name2", "PathTo_Image2");
  dt.Rows.Add("Name3", "PathTo_Image3");
  return dt;
}

private void AddImageColumnToDT(DataTable dt) {
  dt.Columns.Add("Image", typeof(Image));
  string curPath;
  Image curImage;
  foreach (DataRow row in dt.Rows) {
    curPath = row["ImagePath"].ToString();
    curImage = Image.FromFile(curPath);
    row["Image"] = curImage;
  }
}

EDIT*** if the DB returns a "empty" byte[] array column instead of an Image type.编辑*** 如果数据库返回一个“空” byte[]数组列而不是Image类型。

private DataTable GetTableFromDB2() {
  DataTable dt = new DataTable();
  dt.Columns.Add("Name", typeof(string));
  dt.Columns.Add("ImagePath", typeof(string));
  dt.Columns.Add("Image", typeof(byte[]));
  dt.Rows.Add("Name1", "PathTo_Image1");
  dt.Rows.Add("Name2", "PathTo_Image2");
  dt.Rows.Add("Name3", "PathTo_Image3");
  return dt;
}

private void AddImageColumnToDT2(DataTable dt) {
  //dt.Columns.Add("Image", typeof(byte[]));
  string curPath;
  Image curImage;
  byte[] curByteArray;
  foreach (DataRow row in dt.Rows) {
    curPath = row["ImagePath"].ToString();
    curImage = Image.FromFile(curPath);
    curByteArray = imageToByteArray(curImage);
    row["Image"] = curByteArray;
  }
}

public byte[] imageToByteArray(Image imageIn) {
  using (MemoryStream ms = new MemoryStream()) {
    imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
    return ms.ToArray();
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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