none
How to solve CommandText property has not been initialized? RRS feed

  • Question

  • hi am getting this error " CommandText property has not been initialized"

    The code is below:

     private DataTable GetData(string p)
            {
                DataTable dt = new DataTable();
                string constr = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new System.Data.SqlClient.SqlCommand(query))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    sda.Fill(dt);
                }
            }
            return dt;
        }
    }

    Anyone Know help me to solve the issue.


    Divya Diya


    • Edited by Divya Diya Wednesday, February 7, 2018 3:43 AM
    Wednesday, February 7, 2018 3:42 AM

All replies

  • The exception message is giving you a hint that a SELECT query needs to be assigned to the cmd.CommandText property before invoking the Fill method. Make sure the value of the query variable is not null or empty.



    Dan Guzman, Data Platform MVP, http://www.dbdelta.com


    Wednesday, February 7, 2018 4:14 AM
  • Hi Divya Diya,

    Based on your description and related, I create a simple demo, which works, but I am not sure what is the variable named query, where is it come from. I would suggest that you could change the variable name to p, like this:

    private DataTable GetData(string p)
             {
                 DataTable dt = new DataTable();
                 string constr = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
         using (SqlConnection con = new SqlConnection(constr))
         {
             using (SqlCommand cmd = new System.Data.SqlClient.SqlCommand(p))
             {
                 using (SqlDataAdapter sda = new SqlDataAdapter())
                 {
                     cmd.CommandType = CommandType.Text;
                     cmd.Connection = con;
                     sda.SelectCommand = cmd;
                     sda.Fill(dt);
                 }
             }
             return dt;
         }
     }

    #Usage:

     string sqlString = "select * from blogs";
     DataTable dt = GetData(sqlString);

    Best regards,

    Zhanglong


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, February 8, 2018 1:22 AM
    Moderator