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 aNullReferenceExceptionifimgDataisnull. Just compare the value directly withnull.This would be better, as well as immune to that
NullReferenceException: