简体   繁体   中英

How can I set a NULL value for an image

I created a form that load an image then save it into a database.

I want to save the value NULL into the database if the user doesn't select any image.

I tried this code:

drow[1] = string.IsNullOrEmpty(imgData.ToString()) ? DBNull.Value : (object)imgData;

but it gives me this error:

Object reference not set to an instance of an object

this is the code I used to load the image :

private void simpleButton5_Click_1(object sender, EventArgs e)
{
    try
    {
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            picture.ImageLocation = openFileDialog1.FileName;

            imgData = File.ReadAllBytes(openFileDialog1.FileName);
        }
    }
    catch (Exception ex)
    {
        // Could not load the image - probably related to Windows file system permissions.
        XtraMessageBox.Show(String.Format("Cannot display the image.\n You may not have permission to read the file, or it may be corrupt.\n\nReported error: {0}", ex.Message));
    }
}

You are doing some unnecessary things in that line. There is no need to use ToString() and it is in fact harmful, as you will get a NullReferenceException if imgData is null . Just compare the value directly with null .

This would be better, as well as immune to that NullReferenceException :

drow[1] = imgData == null ? DBNull.Value : (object)imgData;

Either the variable drow or imageData is null. They need to reference an object in order to perform array dereference or invoke ToString(). The debugger should be able to show you which variable is the culprit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM