C# .NET 2.0 NullReferenceException

  • Thread starter Thread starter valamas
  • Start date Start date
V

valamas

C# .NET 2.0
whats wrong with my code?
I get an error on the second line saying "NullReferenceException was
unhandled by user code" - "Object reference not set to an instance of
an object."

01 string sql = "select * from myTable";
02 DataTable dtStructure = Database.ExecuteDataTable(sql);


here is my function
public DataTable ExecuteDataTable(string sql)
{
// Conn and Cmd are publics
Cmd.CommandType = CommandType.Text;
Cmd.CommandText = sql;

SqlDataAdapter sqlAdapter = new SqlDataAdapter(Cmd);

DataTable dt = new DataTable("myTable");
sqlAdapter.Fill(dt);

//close our connection
Conn.Close();

//return our DataTable
return dt;
}
 
Try this.
Before you make use of Cmd, create a new instace and try.
that is
Cmd= new Command();


public DataTable ExecuteDataTable(string sql
{
// Conn and Cmd are publics
Cmd = new SqlCommand() //
Cmd.CommandType = CommandType.Text;
Cmd.CommandText = sql;
 
Hi Joby

The problem is not the function, it is this line calling the function.
DataTable dtStructure = Database.ExecuteDataTable(sql)­;

The code dies on that line

thanks
 
Is Database a class of yours? If so, is it a static class? And, have you
declared an instance of the class?
 
Try to put a break point at that line(where you are calling the function),
and examine values of all the variables and see what is null. All so step in
to the function, or a break point at the begining of the function, and see
all the values of the varibles. I really dont see any reason why it is
throwing the exception, with only couple of lines of code it is difficult to
say what is happening.
 
Back
Top