如何为图像设置NULL值
我创建了一个加载图像并将其保存到数据库中的表单。如何为图像设置NULL值
如果用户没有选择任何图像,我想将NULL值保存到数据库中。
我试过这段代码:
drow[1] = string.IsNullOrEmpty(imgData.ToString()) ? DBNull.Value : (object)imgData;
,但它给了我这个错误:
Object reference not set to an instance of an object
这是我用来加载图像的代码:
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));
}
}
你是在这一行中做一些不必要的事情。没有必要使用ToString()
这实际上是有害的,因为如果imgData
是null
,您将获得NullReferenceException
。只需将该值直接与null
进行比较即可。
这将是更好的,以及免疫到NullReferenceException
:
drow[1] = imgData == null ? DBNull.Value : (object)imgData;
感谢它的工作 – 2012-08-05 17:03:37
或(稍微更紧凑): 卓尔[1] = imgData ?? (对象)DBNull.Value; – 2012-08-09 06:11:11
无论是可变卓尔或为imageData为null。他们需要引用一个对象才能执行数组解引用或调用ToString()。调试器应该能够告诉你哪个变量是罪魁祸首。
你为什么在'imgData'上调用'ToString()'?如果'imgData'为'null'则会引发异常。 – Oded 2012-08-05 16:49:52
我认为更多的代码会有所帮助。什么是imgData的类型?卓尔的类型是什么,它的运行时价值是多少? – lesscode 2012-08-05 17:05:23