在 DataGridView 中显示 MySQL 表中存储的二进制格式图片,你需要进行以下步骤:

  1. 创建一个 DataGridView 控件,用于显示图片。
  2. 创建一个 MySQL 连接,并打开连接。
  3. 执行一个 SELECT 查询语句,获取 MySQL 表中的图片数据。
  4. 将查询结果中的二进制图片数据转换为 Image 对象。
  5. 将 Image 对象添加到 DataGridView 的某一列中显示。

下面是一个示例代码,演示了如何实现这些步骤:

using MySql.Data.MySqlClient;
using System;
using System.Data;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

public partial class Form1 : Form
{
    private MySqlConnection connection;
    private MySqlCommand command;
    private MySqlDataAdapter adapter;
    private DataTable table;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // 创建 MySQL 连接字符串
        string connectionString = 'Server=localhost;Database=test;Uid=root;Pwd=123456;';

        // 创建 MySQL 连接
        connection = new MySqlConnection(connectionString);

        try
        {
            // 打开连接
            connection.Open();

            // 创建查询语句
            string query = 'SELECT id, image_data FROM images';

            // 创建 MySQL 命令
            command = new MySqlCommand(query, connection);

            // 创建数据适配器
            adapter = new MySqlDataAdapter(command);

            // 创建数据表
            table = new DataTable();

            // 填充数据表
            adapter.Fill(table);

            // 遍历数据表中的每一行
            foreach (DataRow row in table.Rows)
            {
                // 获取图片数据
                byte[] imageData = (byte[])row['image_data'];

                // 将图片数据转换为 Image 对象
                using (MemoryStream stream = new MemoryStream(imageData))
                {
                    Image image = Image.FromStream(stream);

                    // 将 Image 对象添加到 DataGridView 中的某一列
                    dataGridView1.Rows.Add(row['id'], image);
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show('Error: ' + ex.Message);
        }
        finally
        {
            // 关闭连接
            connection.Close();
        }
    }
}

这个示例中,我们通过执行 SELECT 查询语句从 MySQL 表中获取图片数据,并将数据逐行转换为 Image 对象,然后将 Image 对象添加到 DataGridView 的某一列中显示。请将代码中的连接字符串、查询语句和表名修改为你自己的实际情况。


原文地址: https://www.cveoy.top/t/topic/pg21 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录