如何为图像设置NULL值

时间:2012-08-05 16:48:05

标签: c# sql-server winforms ado.net

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

如果用户没有选择任何图像,我想将值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));
    }
}

2 个答案:

答案 0 :(得分:2)

你正在做那些不必要的事情。没有必要使用ToString(),这实际上是有害的,因为如果NullReferenceException imgData,您将获得null。只需将该值直接与null进行比较。

这会更好,并且不受NullReferenceException的影响:

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

答案 1 :(得分:0)

变量drow或imageData为null。他们需要引用一个对象才能执行数组解除引用或调用ToString()。调试器应该能够显示哪个变量是罪魁祸首。

相关问题