How I can test if I have an image from my sql database or not using C# RRS feed

  • Question

  • I have a winforms Desktop application, That store product from clients, those Product can have an image to descripe them. My problem that when I want to charge my product information, my program show me an execption: System.InvalidCastException : 'Impossible d'effectuer un cast d'un objet de type 'System.DBNull' en type 'System.Byte[]'.' I know that exception causes of I don't have an image into my database. then I want to know how to test if my database has an image first.

    private void chargeImage()
            SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["db"].ConnectionString);
            SqlCommand com1 = new SqlCommand("Select * FROM [dbo].[Product] where RFID = '" + dataview.SelectedRows[0].Cells[0].Value.ToString() + "'", con);//Charge image
            SqlDataReader dr = com1.ExecuteReader();
            if (dr.Read())
                     byte[] picArr = (byte[])dr["image"];
                     ms = new MemoryStream(picArr);
                     ms.Seek(0, SeekOrigin.Begin);
                     pictureBox1.Image = Image.FromStream(ms);

    Tuesday, October 22, 2019 2:58 PM

All replies

  • Try HasRows

    SqlDataReader dr = com1.ExecuteReader();
    if (dr.HasRows())

    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    profile for Karen Payne on Stack Exchange

    Tuesday, October 22, 2019 4:52 PM
  • In order to avoid the error, you can also try this:

       if( dr.Read())


          If( dr.IsDBNull( "image"))


             // no image




             byte [ ] picArr = . . .




    • Edited by Viorel_MVP Wednesday, October 23, 2019 5:37 AM
    • Proposed as answer by MasaSam Wednesday, October 23, 2019 6:22 AM
    Wednesday, October 23, 2019 5:37 AM
  • This only check if there is rows in DataReader. That is not necessary check since Read will return false if there is not rows. The problem is attempt to read column with NULL value.
    Wednesday, October 23, 2019 6:22 AM