0

I have a C# application and within the code I am checking whether a table exist:

// checking whether the table selected from the dataset exists in the database or not
string exists = null;
try
{
    SqlCommand cmd = new SqlCommand("SELECT * FROM sysobjects where name = '" + tbTableName.Text + "'", myConnection);
    exists = cmd.ExecuteScalar().ToString();
}
catch (Exception exce)
{
    MessageBox.Show(exce.Message, "Program Message2", MessageBoxButtons.OK, MessageBoxIcon.Error);
    exists = null;
}

Once that is done, if the table doesn't exist I create a new table, if the table exist I alter the columns if it is missing.

When I run the application and I click a button to check and the above code is run, I get the following error:

Object reference not set to an instance of an object

The table creation or modifying the table code works fine afterward but I am not sure why I am receiving the error.

Any idea how to fix it?

CDspace
  • 2,639
  • 18
  • 30
  • 36
SearchForKnowledge
  • 3,663
  • 9
  • 49
  • 122
  • 3
    Did you debug your code? Maybe `cmd.ExecuteScalar()` returns `null`? Read http://ericlippert.com/2014/03/05/how-to-debug-small-programs/ And [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) By the way, you should always use [parameterized queries](http://blog.codinghorror.com/give-me-parameterized-sql-or-give-me-death/). This kind of string concatenations are open for [SQL Injection](http://en.wikipedia.org/wiki/SQL_injection) attacks. – Soner Gönül Jun 20 '14 at 14:05
  • What line do you get the error? What `Object` is the error referring to? – CDspace Jun 20 '14 at 14:07
  • @CDspace Seems like the sqlCommand cmd line. – SearchForKnowledge Jun 20 '14 at 14:11
  • 1
    I think @C.Evenhuis is correct. You can't do a `.ToString()` on a null, check if it's null before trying to get a string from it – CDspace Jun 20 '14 at 14:14

1 Answers1

3

ExecuteScalar() returns null when no records are returned by the query. So effectively, if no records match the query, the code says:

exists = null.ToString() 
C.Evenhuis
  • 25,996
  • 2
  • 58
  • 72