Wondering if I am going about this the right way. I am creating a C# application that loads a few variables from my App.Config.xml file. I am loading these into a "config" class (Config.cs) along with other variables that I am loading from a MySQL database. This is what my class looks like so far:
class Config
{
public static string ServerHostname = ConfigurationManager.AppSettings["ServerHostname"];
public static string SoftwareVersion = "v0.1a";
public static int StationID = DBConnector.GetStationID();
public static string StationDescription = DBConnector.GetStationDescription();
public static string StationName = ConfigurationManager.AppSettings["StationName"];
}
I am using Config.StationName to pull the Config.StationID and Config.StationDescription from a MySQL database like this in DBConnector.cs:
public static int GetStationID()
{
try
{
MySqlConnection conn = new MySqlConnection(connStr);
conn.Open();
string sql = "select station_id from station_master where station_name = @station_name limit 1";
MySqlCommand cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@station_name", Config.StationName);
object result = cmd.ExecuteScalar();
conn.Close();
return Convert.ToInt32(result);
}
catch (Exception ex)
{
ErrorConnection += ex.ToString();
return 0;
}
}
public static string GetStationDescription()
{
try
{
MySqlConnection conn = new MySqlConnection(connStr);
conn.Open();
string sql = "select station_description from station_master where station_id = '" + Config.StationID +"' limit 1";
MySqlCommand cmd = new MySqlCommand(sql, conn);
// cmd.Parameters.AddWithValue("@station_name", Config.StationName.ToString());
object result = cmd.ExecuteScalar();
conn.Close();
MessageBox.Show(sql);
return (result.ToString());
}
catch (Exception ex)
{
ErrorGenericDBException += ex.ToString();
MessageBox.Show(ErrorGenericDBException);
return "Error";
}
}
The DBConnector.GetStationID class works fine. It returns the int value of my station. But when I try to display the Config.StationDescription, it throws an exception of System.NullReferenceException: Object reference not set to an instance of an object at Namespace.DBConnector.GetStationDescription().
I thought that since I was using a static class for Config.StationName, i don't have to create an instance to refer to it. I need help to understand why its throwing an exception.