An object reference is required for the non-static field, method, or property (variable declaration)

StackOverflow https://stackoverflow.com/questions/20983002

  •  25-09-2022
  •  | 
  •  

Question

I am trying to add a parameter to my query and upon doing so it gives me the above error. I have the variable public I declare outside or my method. I tried making it static as I have read on other posts but it then it gives me the errors every else its referenced. The Method I am working in a public static list method.

Steps taken: Tried declaring a variable in my method t pass the variable to. Online research Tested online research.

Here is my declared variable:

public int CarrierID { get; set; }

Here is my method where I am attempting to add the parameters and where it gives me the error at CarrierID cmd.Parameters.AddWithValue("CarrierID", CarrierID); :

SqlConnection dbConn = new 
   SqlConnection(ConfigurationManager.ConnectionStrings
   ["Connection"].ConnectionString);

   SqlCommand cmd = new SqlCommand();
   cmd.CommandText = sqlString.ToString();
   cmd.Parameters.AddWithValue("CarrierID", CarrierID);

   SqlDataReader reader = null;

   try
   {
      reader = DBHelper.executeQuery(dbConn, sqlString.ToString(), null);
      if (reader != null)
      {
          while (reader.Read())
          {
              EmpData ed = new EmpData();
              ed.CarrierID = (int)reader["CarrierID"];
              list.Add(ed);
           }

empData class:

class EmpData
{
    public int EmployeeID { get; set; }
    public string FName { get; set; }
    public string LName { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public string Email { get; set; }
    public static int CarrierID { get; set; }
    public string CellNumber { get; set; }
    public bool IsActive { get; set; }
    public string CarrierName { get; set; }


    public static List<EmpData> getData()
    {

        List<EmpData> list = new List<EmpData>();

        StringBuilder sqlString = new StringBuilder();
        sqlString.Append("SELECT e.*, c.Carrier ");
        sqlString.Append("FROM Employee e, CellCarrier c ");
        sqlString.Append(" WHERE e.CarrierID = @CarrierID ");
        sqlString.Append("  AND e.CarrierID = c.CarrierID");

        SqlConnection dbConn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = sqlString.ToString();
        cmd.Parameters.AddWithValue("CarrierID", CarrierID);

        SqlDataReader reader = null;

        try
        {
            reader = DBHelper.executeQuery(dbConn, sqlString.ToString(), null);
            if (reader != null)
            {
                while (reader.Read())
                {
                    EmpData ed = new EmpData();
                    ed.EmployeeID = (int)reader["EmployeeID"];
                    ed.FName = reader["FirstName"].ToString();
                    ed.LName = reader["LastName"].ToString();
                    ed.UserName = reader["UserName"].ToString();
                    ed.Password = reader["Password"].ToString();
                    ed.Email = reader["Email"].ToString();
                    ed.CarrierID = (int)reader["CarrierID"];
                    ed.CellNumber = reader["CellNumber"].ToString();
                    ed.IsActive = (bool)reader["IsActive"];
                    ed.CarrierName = reader["Carrier"].ToString();
                    list.Add(ed);
                }
                reader.Close();
                reader.Dispose();
                dbConn.Close();
                dbConn.Dispose();
            }
            else
                throw new Exception("No records returned");
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            if (dbConn != null)
            {
                try { dbConn.Close(); dbConn.Dispose(); }
                catch { }
            }
            if (reader != null)
            {
                try { reader.Close(); reader.Dispose(); }
                catch { }
            }
        }
        return list;
    }
}
Was it helpful?

Solution

Your method is static.. your variable is not.

You need to mark your variable as static for it to be used in static methods:

public static int CarrierID { get; set; }
//     ^^^^^^ this

The other option you have is to remove the static modifier from the method this code is in and instantiate the class it is in before using it.

EDIT:

After your edit.. I think you should change your method to this:

public static List<EmpData> GetData(int carrierId) {
    // code here..

    cmd.Parameters.AddWithValue("CarrierID", carrierId);

    // code here..
}

Then, whenever you call it.. pass in the CarrierID you need:

EmpData.GetData(5);

I assume you already have the required CarrierID available and set.. prior to calling this method (so you can pass it in). I also uppercased the first character of the method.. since that is more in line with C# style.

OTHER TIPS

Ah. Thanks for including your full class. You are trying to use your CarrierID for two purposes -- once to seed your query, and once to store the CarrierID for an EmpData instance. It can't be both. I think what you're trying to do would be best accomplished with a parameter:

public static List<EmpData> getData(int carrierID)
                                    ^^^^^^^^^^^^^
{

    List<EmpData> list = new List<EmpData>();

    StringBuilder sqlString = new StringBuilder();
    sqlString.Append("SELECT e.*, c.Carrier ");
    sqlString.Append("FROM Employee e, CellCarrier c ");
    sqlString.Append(" WHERE e.CarrierID = @CarrierID ");
    sqlString.Append("  AND e.CarrierID = c.CarrierID");

    SqlConnection dbConn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);

    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = sqlString.ToString();
    cmd.Parameters.AddWithValue("CarrierID", carrierID);
                                             ^^^^^^^^^

The problem is that it is an instance variable and you're using it like a static one. So there are three options, the first is to make it a static variable (keep in mind all instances have the same value if that is the case). The option option is to access it from an instance so say it belongs to a class called Carrier then you would need something like;

    Carrier c = new Carrier();
    // anywhere within the same scope as the line above
    cmd.Parameters.AddWithValue("CarrierID", c.CarrierID);

And lastly, you could make it so the method is an instance method in which case you wouldn't get this error when accessing instance variables.

Parameters should start with the @ sign.

try cmd.Parameters.AddWithValue("@CarrierID", CarrierID);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top