How to bind a complex dictionary to a Gridview in

2019-08-09 23:59发布

问题:

I've used an early binding of a dictionary<string, string> to a gridview to show Urls Text and its HRef as key-value and it works like a charm. But since I want to replace the dictionary with this one :

dictionary<string, LinkInfo>

the binding goes wrong! Should I handle some events like as onItemDataBound or something? and the LinkInfo structure is:

public struct LinkInfo{
    public string href;
    public bool Enabled;
}

回答1:

Yes, you need to subsribe to the OnItemDataBound event. Use a template field, insert a literal with an ID like "href"

In the OnItemDataBound event use

Literal _href = e.Row.FindControl("href") as Literal;  
if(_href != null)
{
  _href = ((LinkInfo)e.Row.DataItem).href;
}

Edit: I've written an article that elaborates this topic further: http://www.tomot.de/en-us/article/7/asp.net/gridview-overview-of-different-ways-to-bind-data-to-columns