I built a console application and I’m trying to test if my application works as expected.
I create an instance of the API class as shown in the code below but I receive an error:
An object reference is required for the non-static field. I’ve already checked similar issues like this one but it seems different. What am I doing wrong?
namespace ConsoleApplication1
{
class Api
{
String ConStr = "SERVER=myservername; Database=mydb; UID=mylogin; PWD=mypassword;encrypt=no;enlist=false";
String bin_Num = "201284-11-000";
Label lblResults;
static void Main(string[] args)
{
Api Test_api = new Api();
Test_api.getQualWeight(ConStr, bin_Num, lblResults);
}
public Dictionary<String, String> getQualWeight(String sqlConStr, String inBin, Label lblResults)
{
Dictionary<String, String> qualList = new Dictionary<string, string>();
string selectSQL = "select Name,qual_weight from Qualification_type "
+ "where ID in (select Qualification_ID from Qualifications where BIN = @inBin)";
con = getConn(sqlConStr);
SqlCommand cmd = new SqlCommand(selectSQL, con);
cmd.Parameters.AddWithValue("@inBin", inBin);
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
qualList.Add(reader[0].ToString(), reader[1].ToString());
}
reader.Close();
return qualList;
}
catch (Exception err)
{
lblResults.Text = "error fetching qualification weight " + err.Message;
return null;
}
finally
{
con.Close();
}
}
}
}
If you want to use an
Objectand not have all the members be static you need to reference the non-static member variables using an instance of the class.Change:
To:
Because
ConStr,bin_Num, andlblResultsare instance variables they must be references with an instance of the class – in this caseTest_api.Alternately, you could move those values into a global, static, scope by changing their declarations from:
To this: