Reputation: 249
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));
}
}
Upvotes: 0
Views: 5750
Reputation: 6361
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.
Upvotes: 0
Reputation: 499112
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;
Upvotes: 2