Parameter is not a valid exception in C #

I wrote the following code to transfer an image from a database to a picure window in C #. I got this code from microsoft. Where is the URL of this page. Microsoft

When I run this code, the display parameter is not a valid exception.

What is wrong with this code?

private void button2_Click(object sender, EventArgs e) { try { String strCn =@ "Data Source=DESKTOP-ROF2H0M\BHAGI;Initial Catalog=Golden;Integrated Security=True"; SqlConnection cn = new SqlConnection(strCn); cn.Open(); //Retrieve BLOB from database into DataSet. SqlCommand cmd = new SqlCommand("SELECT User_id ,img FROM login", cn); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds, "login"); int c = ds.Tables["login"].Rows.Count; if (c > 0) { //BLOB is read into Byte array, then used to construct MemoryStream, //then passed to PictureBox. Byte[] byteBLOBData = new Byte[0]; byteBLOBData = (Byte[])(ds.Tables["login"].Rows[c-1]["img"]); MemoryStream stmBLOBData = new MemoryStream(byteBLOBData); pictureBox1.Image = Image.FromStream(stmBLOBData); } cn.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } 

The following error message has appeared.

An unhandled exception of type "System.ArgumentException" occurred in System.Drawing.dll

Additional Information: The parameter is not valid.

Here is the binding of my database. LOgin table

+5
source share
1 answer

You have 3 problems (performance and security issue):

  • You need to process the SQL connection
  • You need to store files (binary and images) on disk (without a database)
  • Never try to store user password without encryption (e.g. MD5)

 private void button2_Click(object sender, EventArgs e) { string strCn = @"Data Source=DESKTOP-ROF2H0M\BHAGI;Initial Catalog=Golden;Integrated Security=True"; using (var cn = new SqlConnection(strCn)) { try { cn.Open(); using (var cmd = new SqlCommand("SELECT User_id ,imgUrlOnDisk FROM login", cn)) { using (var dr = cmd.ExecuteReader()) { if (dr.HasRows) { if (dr.Read()) { pictureBox1.Image = Image.FromFile(Convert.ToString(dr["imgUrlOnDisk"])); } } } } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { if (cn.State != ConnectionState.Closed) { cn.Close(); } } } } 

The best way to suggest you use an ADO.net request:

 try { using (SqlCommand cmd = new SqlCommand(Query, Connection)) { try { cmd.CommandType = CommandType; foreach (var p in InParameters) { cmd.Parameters.Add(p); } cmd.Connection.Open(); affectedRows = cmd.ExecuteNonQuery(); if (affectedRows == 0) { //Zero Record Success } else { if (affectedRows > 1) { //Many Record Success } else { //One Record Success } } } catch (Exception InnerEx) { //Handle your error } finally { if (cmd.Connection.State != ConnectionState.Closed) { cmd.Connection.Close(); } } } } 
+2
source