0

I want to retrieve the data from database. When I alter my code to image its showing parameter not valid.

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

ADDED from OP's Comment

for loading i use this code

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);
pooja
  • 37
  • 1
  • 1
  • 5
  • 5
    What line does the error occur on? – Tim Jul 04 '13 at 11:31
  • 5
    you should really have a look at [sqlParameter](http://msdn.microsoft.com/en-ca/library/system.data.sqlclient.sqlparameter%28v=vs.110%29.aspx). Your code is weak to [sql Injection](http://en.wikipedia.org/wiki/SQL_injection) – Rémi Jul 04 '13 at 11:31
  • 2
    Possible duplicate http://stackoverflow.com/questions/629955/parameter-not-valid-exception-loading-system-drawing-image – Panagiotis Kanavos Jul 04 '13 at 11:33
  • error near system.drawing.image.fromstream as parameter not valid. i m beginner so kindly teach me what can be done – pooja Jul 04 '13 at 11:33
  • 1
    IF the error appears when constructing the image from the MemoryStream, it may be that what you loaded is not a valid image. What is the content of the 'Image' field? What image type, format? How do you load it? – Panagiotis Kanavos Jul 04 '13 at 11:34
  • @im_a_noob Not everyone is worried about SQL Injection attacks. – MoonKnight Jul 04 '13 at 11:36
  • 4
    @Killercam whoever isn't worried about SQL Injection attacks should be locked up – Panagiotis Kanavos Jul 04 '13 at 11:36
  • 2
    You're leaving yourself wide open to SQL injection. You should google that, as well as "parameterized queries", to learn how to avoid it. – Jeremy Wiggins Jul 04 '13 at 11:36
  • @Killercam I know that. But at least by showing him that he is prone to that is a good thing. Maybe not for him but it will most likely help some one else – Rémi Jul 04 '13 at 11:38
  • jpg valid image only. its adding properly in database but i don't know to retrieve tat back – pooja Jul 04 '13 at 11:42
  • @PanagiotisKanavos I am well aware of the problems of injection and I _do_ use them where transactions across networks are concerned. But, for an purely off-line app that uses SQL Server as back-end _on a local machine_ (yes, there are plenty of these types of apps) why worry about complicating things. If my users want to hack my/their application and corrupt their own databases locally, great, I don't care what-so-ever. Writing parameterised queries all day is a waste of my time in this case. – MoonKnight Jul 04 '13 at 11:42
  • 6
    @Killercam a lot of people probably aren't worried about falling in a hole either, but if I saw someone blindly headed towards one, I'd still give them a heads up. – Jeremy Wiggins Jul 04 '13 at 11:42
  • for loading i use this code 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); – pooja Jul 04 '13 at 11:42
  • @JeremyWiggins fair enough, but you get people on here blindly suggesting the a localised application with 1000s of SQL queries running on a local machine should use parameters at all costs - this is _not true_. There are cases where the hassle of parameterising you queries is a waste of resources and people should be aware of this. – MoonKnight Jul 04 '13 at 11:44
  • What is the `image` field's type – Panagiotis Kanavos Jul 04 '13 at 11:45
  • 1
    @Killercam SQL injections occur when any user types a goofy entry in a textbox. Doesn't matter if it's on a local or remote machine or if it's localized or not. And a non-parameterized query run 1000 times will result in a performance hit compared to parameterized queries due to execution plan recompilation – Panagiotis Kanavos Jul 04 '13 at 11:47
  • 2
    I'll repeat Tim's question: Which line does the error occur on? – Vilx- Jul 04 '13 at 11:49
  • @PanagiotisKanavos yes its field type – pooja Jul 04 '13 at 11:52
  • @PanagiotisKanavos No, there is no performance hit. The query compilation plan of a query is cashed/held by the server and has nothing to do with the way the CLR handles and sends the query to the server. This is another misnomer, unless you can point me to some docs that say otherwise. "SQL injections occur when any user types a goofy entry in a textbox", no, they can most commonly occur in string inside your code, as I said, if it is a local machine with local SQL instance - I don't care if the user writes something goofy which I pass to SQL Server and he then hacks, why would I? – MoonKnight Jul 04 '13 at 11:54

1 Answers1

0

Please let me know if this works:

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

You can also use a using block with the SqlConnection as in this SO question. Also please note that it is better to not use Select * from ... but name the columns. You can read more about it on these links:

Community
  • 1
  • 1
JP Hellemons
  • 5,977
  • 11
  • 63
  • 128
  • 1
    @pooja You're not being specific enough to allow people to help you. You've been asked twice now, "Which line does the error occur on?", and you still haven't given an answer. So, please edit your question to include both the exact line which is causing the error and also **the exact error message** you are getting. – John H Jul 04 '13 at 12:44
  • @JohnH i m not getting error sir. its saying parameter not valid while retrieving. something wrong near memory stream which i dont know to fig out – pooja Jul 04 '13 at 12:55
  • LOL! So it must be something like an invalid or no byte array in the database? Perhaps add some `Response.Write(variableGoesHere)` or put some breakpoints in Visual Studio etc. There is enough info in all the other comments to troubleshoot this. – JP Hellemons Jul 05 '13 at 07:08