gpt4 book ai didi

c# - 从 mysql 数据库将图像加载到 picturebox 时出错。空引用异常

转载 作者:行者123 更新时间:2023-11-28 23:37:16 26 4
gpt4 key购买 nike

我正在尝试从数据库中获取图像并显示到图片框中。我的代码在下面

private void getImage()
{
using (MySqlConnection conn = new MySqlConnection(connectionManager.connectionString))
{
try
{
conn.Open();

string query = "SELECT 'Image' FROM student_img WHERE ID = @ID";

MySqlCommand cmd = new MySqlCommand(query, conn);

int id = 10;
cmd.Parameters.AddWithValue("@ID", id);

var da = new MySqlDataAdapter(cmd);
var ds = new DataSet();
da.Fill(ds, "Image");
int count = ds.Tables["Images"].Rows.Count;

if (count > 0)
{
var data = (Byte[])(ds.Tables["Images"].Rows[count - 1]["Image"]);
var stream = new MemoryStream(data);
picLogo.Image = Image.FromStream(stream);
}
}
catch (Exception ex)
{
MessageBox.Show("Connection Error!\n" + ex.Message, "Error Message",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

}

但我收到 NullReferenceException 错误。我还有另一种方法,也许我可以以某种方式使用它,但我不确定如何从数据库中获取数据,因为我是 C# 的新手

public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}

最佳答案

设法解决问题,不得不改变

Images

Image

private void getImage()
{
using (MySqlConnection conn = new MySqlConnection(connectionManager.connectionString))
{
try
{
conn.Open();

string query = "SELECT Image FROM student_img WHERE ID = @ID";

MySqlCommand cmd = new MySqlCommand(query, conn);

int id = 10;
cmd.Parameters.AddWithValue("@ID", id);

var da = new MySqlDataAdapter(cmd);
var ds = new DataSet();
da.Fill(ds, "Image");
int count = ds.Tables["Image"].Rows.Count;

if (count > 0)
{
var data = (Byte[])(ds.Tables["Image"].Rows[count - 1]["Image"]);
var stream = new MemoryStream(data);
picLogo.Image = Image.FromStream(stream);
}

}
catch (Exception ex)
{
MessageBox.Show("Connection Error!\n" + ex.Message, "Error Message",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

}

关于c# - 从 mysql 数据库将图像加载到 picturebox 时出错。空引用异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35420283/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com