Search code examples
c#dictionarystaticenumerationidictionary

How do I enumerate a static dictionary contained in a static class from asp.net ( aspx) page


I don't understand how to loop over a static dictionary contained in a static class from my aspx page. I have this for the static class

public static class ErrorCode  

{
    public static IDictionary<int, string> ErrorCodeDic;

    static ErrorCode()
    {
        ErrorCodeDic = new Dictionary<int, string>()
        { 
            {1, "a problem"},
            {2, "b problem"}
        };
    }
}

MORE SPECIFIC I can get it to work by spelling it out like this in the aspx part

foreach( System.Collections.generic.KeyValuePair<int, string> kvp in MyLibrary.Dictionaries.ErrorCode.ErrorCodeDic) 

But I thought I could shorthand it by declaring variables in the code behind?

Public KeyValuePair<int, string> error;
Public ErrorCode.ErrorCodeDic ErrorCodes; OR
Public ErrorCode.ErrorCodeDic ErrorCodes = ErrorCode.ErrorCodeDic; "

I get build errors "The type name 'ErrorCodeDic' does not exist in the type ErrorCode.

And then in the aspx page use

foreach( error in ErrorCodes)

Solution

  • You can loop over all pairs like this:

    foreach( KeyValuePair<int, string> kvp in ErrorCode.ErrorCodeDic)
    {
      Response.Write(string.Format("Key = {0}, Value = {1}", kvp.Key, kvp.Value));
    }
    

    For your updated case, in the code-behind:

    public IDictionary<int, string> ErrorCodes = MyLibrary.Dictionaries.ErrorCode.ErrorCodeDic;
    

    in the aspx:

    foreach(var error in ErrorCodes) { }
    

    Alternatively, nothing in the codebehind, and this in the aspx:

    <%@ Import Namespace="MyLibrary.Dictionaries" %>
    ....Content...
    <% foreach(var error in ErrorCode.ErrorCodeDic) { %>
      .. something ..
    <% } %>