-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;
            }
        }
3
  • Add error with stack trace to the question Commented Dec 24, 2018 at 18:26
  • You should... probably read the error message. Commented Dec 24, 2018 at 21:32
  • If throw; is the only thing you do in a catch you might as well get rid of the whole try/catch. Commented Dec 25, 2018 at 10:40

1 Answer 1

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())
     { 
          ....
     }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.