[英]Error loading image to picturebox from mysql database. NullReferenceException
我正在嘗試從數據庫中獲取圖像並顯示到圖片框中。 我的代碼如下
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;
}
設法解決問題,不得不改變
圖片
至
圖片
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);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.