1

I have Oledbconnection like this(this is sample code):

public string var1, var2;
...
OleDbConnection Connection;
    Connection = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=" +
               Server.MapPath("~/db.mdb"));

OleDbCommand Command1, Command2;

Command1 = new OleDbCommand("SELECT DT FROM Table1 WHERE ID = 1", Connection);
Command2 = new OleDbCommand("SELECT GT FROM Table1 WHERE ID = 1", Connection);

Connection.Open();
var1= (string)Command1.ExecuteScalar();
var2= (string)Command2.ExecuteScalar();
Connection.Close();

When Oledbcommand getting null, ExecuteScalar getting error.

I can use try-catch or I can control if object is null or not. But is it possible easy way to do it? I just want if query getting null, I want to set null var1 and var2.

Thank you.

onur
  • 5,647
  • 3
  • 23
  • 46
  • I don't understand. Just check `if(var1 == null)` or something? – Soner Gönül May 08 '15 at 11:53
  • Implement a null check, – Dhrumil May 08 '15 at 11:53
  • if query null, i want to set like this: `var1 = "";`. Because if oledbcommand getting null, executescalar does not work. – onur May 08 '15 at 11:55
  • 1
    for assigning you can use the null coalescing operator var1= (string) (Command1.ExecuteScalar() ?? ""); which means "" is returned if execute Scalar is returning null. Don`t forget to check for dbnull afterwards – Marc Wittmann May 08 '15 at 12:00

1 Answers1

3

you have to check if the return value equals DBNull

var result1 = Command1.ExecuteScalar(); //you get an object here, not a string
if (result1 != DBNull.Value && result1 != null)
{
   var1 = (string)result1;
}
fubo
  • 44,811
  • 17
  • 103
  • 137