如何将数据从数据库加载到DataGridView?

时间:2017-09-03 03:14:31

标签: c# sql-server winforms datagridview

我试图将数据从数据库加载到dataGridView中,当选择了一行时,记录将显示在其他控件上,但它可以正常工作但不是预期的,特别是当图像列上有空值时,我不知道下一步该怎么做

这是我的桌面结构:

TABLE TblProduct
[ProductID]   INT            IDENTITY (1, 1) NOT NULL,
[ProductType] INT            NOT NULL,
[Description] NVARCHAR (MAX) NULL,
[Price]       MONEY          NULL,
[Image]       IMAGE          NULL,

这是我的Retrieve()方法:

private void Retrieve()
{
    dataGridView1.Rows.Clear();

    string sql = "SELECT * FROM TblProduct";
    cmd = new SqlCommand(sql, connection);
    connection.Open();
    adapter = new SqlDataAdapter(cmd);
    adapter.Fill(dt);       

    foreach (DataRow row in dt.Rows)
    {                
        dataGridView1.Rows.Add(row[0].ToString(), row[1].ToString(), row[2].ToString(), Convert.ToDecimal(row[3]), row["Image"]);
    }
    connection.Close();
    dt.Rows.Clear();
}

这是我的MouseClick事件:

private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
    typeTxt.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
    descriptionTxt.Text = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
    priceTxt.Text = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();
    pictureBox1.Image = (Image)dataGridView1.SelectedRows[0].Cells["Image"].Value;            
}

这是我在dataGridView上选择有图像的行时得到的例外

System.InvalidCastException: 'Unable to cast object of type 'System.Byte[]' to type 'System.Drawing.Image'.'

在dataGridView上选择没有图像的行时

System.InvalidCastException: 'Unable to cast object of type 'System.DBNull' to type 'System.Drawing.Image'.'

1 个答案:

答案 0 :(得分:2)

您必须从字节数组创建Image并检查DB nulls。

var value = dataGridView1.SelectedRows[0].Cells["Image"].Value
if(value != DBNull.Value)
{
   byte[] data = (byte[]) value;
   MemoryStream ms = new MemoryStream(data);
   pictureBox1.Image = Image.FromStream(ms);
}