首页 > 解决方案 > 如何检查图像是否存在于数据库中并在 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);
        }
    }

请帮忙....

标签: c#.netdatabasewinformssqlite

解决方案


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());


推荐阅读