开发者

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

开发者 https://www.devze.com 2022-12-21 22:27 出处:网络
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

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)


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 ..
<% } %>
0

精彩评论

暂无评论...
验证码 换一张
取 消