I would like to have a dictionary object contains string keys and values, which are generated from the database. But, I only need to run once when page loads. (C# .NET)
In which way can I do that? I tried the following:
public static class GlobalVar
{
static Dictionary<string, string> GenerateLoginStatus(Dictionary<string, string> List)
{
string Query = "SELECT * FROM LoginStatus";
DataTable Types = MyAdoHelper.ExecuteDataTable(GlobalVar.dbName, Query);
foreach (DataRow Row in Types.Rows)
{
List.Add(Row["Status_Title"].ToString(), Row["Status_Info"].ToString());
}
return List;
}
public const string GlobalString = "ProjectDatabase.mdf";
public static Dictionary<string, string> LoginTypes = GenerateLoginStatus(LoginTypes);
}
Table structure:
Status_Title Status_Info
AlreadyLoggedIn User is already logged in.
A B
C D
And I use it in another page: GlobalVar.LoginStatus["AlreadyLoggedIn"]
The “AlreadyLoggedIn” is created in the database for sure, but when I call any of the keys, it returns an exception (doesn’t tell which exception).
EDIT: I changed the code a bit, and it now gives “The type initializer for ‘GlobalVar’ threw an exception.”
I suppose you might be getting null reference exception which is caused because you call your static initialization method with instance you want to initialize (
LoginTypes):When
GenerateLoginStatusexecutes,LoginTypesis null. Yet you attempt to add items to it:This causes null reference exception. You should use type constructor and create that dictionary there: