所以我在sql server上的BikeStore数据库中有一个名为Bicycle的表,由以下列组成: BID,BName,描述,BType,品牌,原产地,价格,股票,BImage
只需单击datagridview上的单元格,即可成功将所有文本框和一个组合框与来自sql server的数据绑定。以下是代码:
private void dg1_CellClick(object sender, DataGridViewCellEventArgs e)
{
bidTxt.Text = dg1.SelectedRows[0].Cells[0].Value.ToString();
bnameTxt.Text = dg1.SelectedRows[0].Cells[1].Value.ToString();
bdescrichTxt.Text = dg1.SelectedRows[0].Cells[2].Value.ToString();
typeCB.Text = dg1.SelectedRows[0].Cells[3].Value.ToString();
brandTxt.Text = dg1.SelectedRows[0].Cells[4].Value.ToString();
originTxt.Text = dg1.SelectedRows[0].Cells[5].Value.ToString();
priceTxt.Text = dg1.SelectedRows[0].Cells[6].Value.ToString();
stockTxt.Text = dg1.SelectedRows[0].Cells[7].Value.ToString();
但每次我尝试加载图片时它仍然会生成错误。这是代码:
sqlconn.Open();
SqlCommand cmd = new SqlCommand("SELECT BImage FROM Bicycle WHERE BID = " + dg1.SelectedRows[0].Cells[0].Value + "", sqlconn);
da.SelectCommand = cmd;
DataSet ds = new DataSet();
byte[] mydata = new byte[0];
da.Fill(ds, "Bicycle");
DataRow myrow;
myrow = ds.Tables["Bicycle"].Rows[8];
mydata = (byte[])myrow["BImage"];
MemoryStream stream = new MemoryStream(mydata);
BikePic.Image = Image.FromStream(stream);
sqlconn.Close();
}
我做错了什么?
我是新来的。
答案 0 :(得分:0)
如果它只是检索该查询的BLOB,那么你可以做一些更简单的事情:
// SqlConnection creation and opening omitted
using(SqlCommand cmd = new SqlCommand("SELECT BImage FROM Bicycle WHERE BID = " + dg1.SelectedRows[0].Cells[0].Value + "", sqlconn))
{
byte[] mydata = (byte[])cmd.ExecuteScalar();
MemoryStream stream = new MemoryStream(mydata);
BikePic.Image = Image.FromStream(stream);
}
此外,您可能希望在创建stream
控件后处置Image
,但我不完全确定。
答案 1 :(得分:0)
问题解决了!在 blockquote 之间的SqlCommand行添加单引号,因为它会搜索您要查找的ID,如下所示:
SqlCommand cmd = new SqlCommand("SELECT BImage FROM Bicycle WHERE BID = '" + dg1.SelectedRows[0].Cells[0].Value + "'", sqlconn);
以下是修改后的代码 。看到区别?
SqlCommand cmd = new SqlCommand("SELECT BImage FROM Bicycle WHERE BID = " + dg1.SelectedRows[0].Cells[0].Value + "", sqlconn);
哈哈傻傻的我。 无论如何,谢谢你们!