我想从数据库中检索数据。当我改变我的代码以使其显示参数无效时。
private void button7_Click(object sender, EventArgs e)
{
ProductDetails.Items.Clear();
SqlConnection con = new SqlConnection(@"server=xxx-PC; database= sample; integrated security= true");
con.Open();
SqlCommand cmd = new SqlCommand("select * from tblproduct where prodname like '" + textBox1.Text + "%';", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
byte[]imgg =(byte[])(dr["image"]);
if(imgg==null)
pictureBox1.Image= null;
else
{ //i m not getting error it says parameter not valid below//
MemoryStream mstream = new MemoryStream(imgg);
pictureBox1.Image = System.Drawing.Image.FromStream(mstream);
}
ProductDetails.Items.Add(dr[0].ToString() + " \t" + dr[1].ToString() + "\t" + dr[2].ToString()+ dr[3].ToString());
}
}
从OP的评论中添加
用于加载我使用此代码
byte[] imagebt = null;
FileStream fstream = new FileStream(this.textBox5.Text, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fstream);
imagebt = br.ReadBytes((int)fstream.Length);
答案 0 :(得分:0)
如果有效,请告诉我:
private void button7_Click(object sender, EventArgs e)
{
ProductDetails.Items.Clear();
SqlConnection con = new SqlConnection(@"server=xxx-PC; database= sample; integrated security= true");
SqlCommand cmd = new SqlCommand("select * from tblproduct where prodname like @name;", con);
cmd.Parameters.AddWithValue(textBox1.Text.Trim() + "%");
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
try
{
con.Open();
da.Fill(dt);
}
catch (Exception e)
{ //exception handling here }
finally { con.Close(); }
foreach(DataRow dr in dt.Rows)
{
byte[]imgg =(byte[])dr["image"];
if(imgg==null || imgg.length <= 0)
pictureBox1.Image= null;
else
{
pictureBox1.Image = ByteToImage(imgg);
}
ProductDetails.Items.Add(dr[0].ToString() + " \t" +
dr[1].ToString() + "\t" +
dr[2].ToString() +
dr[3].ToString());
}
}
// https://stackoverflow.com/questions/9576868/how-to-put-image-in-a-picture-box-from-a-byte-in-c-sharp
public static Bitmap ByteToImage(byte[] blob)
{
MemoryStream mStream = new MemoryStream();
byte[] pData = blob;
mStream.Write(pData, 0, Convert.ToInt32(pData.Length));
Bitmap bm = new Bitmap(mStream, false);
mStream.Dispose();
return bm;
}
您还可以使用与this SO question中的using
一样的SqlConnection
块。
另请注意,最好不使用Select * from ...
,但请为列命名。
您可以在以下链接中阅读更多相关信息: