-3

I am Getting the error while executing the code, CommandText Property has been not initialized

  public DataTable Mappingdataload(string name)
        {
            try
            {
                string spname = "";
                switch (name.ToLower())
                {
                    case "student":
                        spname = "RetrieveStudent";
                        break;
                    case "organization":
                        spname = "RetrieveOrganization";
                        break;
                }
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = SQLConClass.GetSQLConnection();
                cmd.CommandText = spname;
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(cmd);
                DataTable dataTable = new DataTable();
                sqlDataAdapter.Fill(dataTable);
                return dataTable;
            }
            catch (Exception)
            {
                throw;
            }
        }
Derviş Kayımbaşıoğlu
  • 28,492
  • 4
  • 50
  • 72

1 Answers1

0

you are getting this error because command text is not initialized :)

It is always better to first make connection and then create command. check the code below.

var conn = SQLConClass.GetSQLConnection();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = spname;
cmd.CommandType = CommandType.StoredProcedure;

also better to use it like this:

using (var conn = SQLConClass.GetSQLConnection())
using (SqlCommand cmd = conn.CreateCommand())
{ 
     cmd.CommandText = spname;
     cmd.CommandType = CommandType.StoredProcedure;
     using (var reader = cmd.ExecuteReader())
     { 
          ....
     }
}
Derviş Kayımbaşıoğlu
  • 28,492
  • 4
  • 50
  • 72