参数无效
本文关键字:无效 参数 | 更新日期: 2023-09-27 18:20:55
我想从数据库中检索数据。当我修改我的代码以显示图像时,它的显示参数无效。
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);
请告诉我这是否有效:
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;
}
您也可以将using
块和SqlConnection
一起使用,如本SO问题中所述。另外请注意,最好不要使用Select * from ...
,而是命名列。你可以在以下链接上阅读更多关于它的信息:
- http://satheeqhassan.blogspot.nl/2012/10/why-is-bad-practice-in-t-sql_3.html
- http://www.toadworld.com/platforms/sql-server/b/weblog/archive/2012/07/27/how-to-prevent-select-the-evil-way.aspx