MrASifuMason
MrASifuMason

Reputation: 21

C# Cannot implicitly convert type System.DBNull to string

Cannot implicitly convert type 'System.DBNull' to 'string'

I am trying to pull data from a worksheet and I get the above error. It happens on the string Text line. What can I do convert this or ignore the null?

var excel = new Microsoft.Office.Interop.Excel.Application();
Workbook workbook =  excel.Workbooks.Open(@"C:\Documents\ANIs.xlsx");
Worksheet worksheet = workbook.Worksheets[1];

    Range a1 = worksheet.get_Range("A1","B2");

    object rawValue = a1.Value;
    string Text = a1.Text; //<--Error Occurs here. 

    for (int i = 0; i < a1.Count; i++)
    {
        if (a1.Text != null)
            Console.WriteLine("{1}", rawValue, Text);
    }
    Console.ReadLine();
}

Upvotes: 1

Views: 5680

Answers (1)

Greg
Greg

Reputation: 11480

Basically, you need a Conditional Statement. If you call ToString() on certain types, if it is Null it will throw an exception. The easiest remedy would be:

if(!(a1 is DBNull))
{
     // Do Something
}

Hopefully this clarifies a bit.

// Sample:
var range = worksheet.get_Range("A1","B2");
if(!(range is DBNull))
{
     object raw = range.Value;
     string text = range.Text;

     // Loop here
}

Also, you need to not use Text as capital, that is predefined and can't be used as a variable. Another error in the code. Note in comments, what @RonBeyer said about the Text being used.

Upvotes: 1

Related Questions