1
我试图从数据库中加载数据到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,
这里是我的检索()方法:
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();
}
这里是我的鼠标点击事件:
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;
}
这里有具有图像
System.InvalidCastException: 'Unable to cast object of type 'System.Byte[]' to type 'System.Drawing.Image'.'
DataGridView中选择一行时,选择上有没有像DataGridView中的行,当我得到的例外
System.InvalidCastException: 'Unable to cast object of type 'System.DBNull' to type 'System.Drawing.Image'.'
对不起,它没有工作,我把它放在我的foreach循环中,会得到这个异常:System.ArgumentOutOfRangeException:'索引超出范围。必须是非负数且小于集合的大小。 参数名称:index' –
我想通了,我把它放在错误的地方,我把它放在MouseClick事件中,现在它可以工作,非常感谢Jan –
欢迎。如果它适合你,不要忘记关闭这个问题。谢谢! –