"Unable to cast object of type 'System.Byte[]' to type 'System.IConvertible'." error in Photo: why and how do I fix it?

My code below gives the error “Unable to cast object of type ‘System.Byte[]’ to type ‘System.IConvertible’.”

protected void btnSubmit_Click(object sender, EventArgs e)
    if (fpPhoto.HasFile)         
        if (fpPhoto.PostedFile.ContentType == "image/jpg" 
            || fpPhoto.PostedFile.ContentType == "image/jpeg" 
            || fpPhoto.PostedFile.ContentType == "image/png") 
            int filelenght = fpPhoto.PostedFile.ContentLength;  
            imagebytes = fpPhoto.FileBytes;   
            //fpPhoto.PostedFile.InputStream.Read(imagebytes, 0, filelenght);   
    User objUser = new User();  

    objUser.UserName_Pk = txtUserName.Text; 
    objUser.Password = txtPassword.Text;    
    objUser.MobileNo = txtMobileNo.Text;    
    objUser.Email = txtEmail.Text;        
    objUser.SecurityAnswer = txtAnswer.Text;        
    objUser.Photo = Convert.ToByte( imagebytes);  

Why do I get this error, and how can I fix it?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

I assume that imageBytes is an array of bytes (byte[]). As your code compiles, the Photo property must be of type byte. You try to convert the byte array to a single byte in this line:

objUser.Photo = Convert.ToByte( imagebytes);  

This leads to an exception as the byte array does not implement IConvertible which would be required in order for the conversion to work. But how would you want to convert a byte array to a single byte anyway? How should the conversion mechanism know which byte of the array to assign to the single byte? Therefore I suspect that you’d rather want the Photo property to also be of type byte[] so that it is able to store the complete picture and not only one byte of it.

So in order to fix this, try to change the property in your Entity to byte[] (which might also involve changing the database schema) and assign the array directly without using Convert.ToByte().

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply