如何为图像设置NULL值

本文关键字:NULL 设置 图像 | 更新日期: 2024-10-20 22:51:41

我创建了一个表单,加载图像,然后将其保存到数据库中。

如果用户没有选择任何图像,我想将值NULL保存到数据库中。

我试过这个代码:

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

但它给了我一个错误:

对象引用未设置为对象的实例

这是我用来加载图像的代码:

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

如何为图像设置NULL值

您在这一行中做了一些不必要的事情。没有必要使用ToString(),事实上它是有害的,因为如果imgDatanull,则会得到NullReferenceException。直接将该值与null进行比较即可。

这会更好,并且对NullReferenceException:免疫

drow[1] = imgData == null ? DBNull.Value : (object)imgData;
变量drow或imageData为null。它们需要引用一个对象才能执行数组解引用或调用ToString()。调试器应该能够显示哪个变量是罪魁祸首。