c# - 如何检查图像是否存在于数据库中并在 c# windows 应用程序中使用组合框值显示在图片框中
问题描述
我正在使用 Windows 窗体,我编写了一个代码,用于在选择组合框值时从图片框中的数据库中获取图像。my code is working correctly when combo box value is select and show the data (only show data that have a image). 但是我有一个没有图像的数据,当我选择组合框值来显示没有图像的数据时,它会显示“错误”-“参数无效”。
我尝试了条件,但代码对我不起作用。
这是代码...
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
using (SQLiteConnection conn = new SQLiteConnection("Data Source=combolist.db;Version=3;"))
{
string CommandText = "SELECT * FROM combo WHERE [Id]=@id";
using (SQLiteCommand cmd = new SQLiteCommand(CommandText, conn))
{
cmd.Parameters.AddWithValue("@id", comboBox1.SelectedItem.ToString());
conn.Open();
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
textBox1.Text = dr["Id"].ToString();
textBox2.Text = dr["FirstName"].ToString();
textBox3.Text = dr["LastName"].ToString();
textBox4.Text = dr["Age"].ToString();
textBox5.Text = dr["Address"].ToString();
byte[] img = (byte[])(dr["Pic"]);
if (img == null)
{
pictureBox1.Image = null;
}
else
{
MemoryStream ms = new MemoryStream(img);
pictureBox1.Image = System.Drawing.Image.FromStream(ms);
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
请帮忙....
解决方案
byte[] img = (byte[])(dr["Pic"]);
如果值为 null,则此强制转换抛出错误。
我会检查是否dr["Pic"] != null
然后:
if(dr["Pic"] != null){
MemoryStream ms = new MemoryStream((byte[])(dr["Pic"]));
pictureBox1.Image = ms != null ? System.Drawing.Image.FromStream(ms) : null;
} else {
pictureBox1.Visible = false;
//or pictureBox1.Image = null;
}
更新:
这:cmd.Parameters.AddWithValue("@id", comboBox1.SelectedItem.ToString());
应该是cmd.Parameters.AddWithValue("@id", comboBox1.SelectedValue.ToString());
推荐阅读
- javascript - 我有一个显示用户当前个人资料图像的图像元素。我可以将该图像的 src 更改为文件输入中的图像吗?
- nginx - 试图过度工作来使用子域的 wallabg 根要求
- go - Go sync.pool 比 make 慢很多吗?
- javascript - 用 ajax 响应数据替换部分视图
- linux - Perl 搜索和替换
- mysql - MySQL Workbench,不断收到错误 1064 错误
- angular - CanLoad、Lazy 模块和 take(1)
- symfony - 使用迁移管理数据的 Symfony Doctrine 只读实体
- python - 具有 SyncManager 类的 python 中多进程优先级队列的队列函数
- python - 如何在一列Python中打印出具有最大值的CSV文件行