0

我想从数据库中检索数据。当我更改我的代码以使其显示参数无效时。

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);
4

1 回答 1

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;
}

您也可以在这个 SO question中使用带有as的using块。另请注意,最好不要使用但命名列。您可以在这些链接上阅读更多相关信息:SqlConnectionSelect * from ...

于 2013-07-04T12:05:11.467 回答