John
John

Reputation: 17491

ASP.Net GridView: BoundField using Indexer instead of Property

I have a class where the majority of its data is contained in a Dictionary like so:

public class Document
{
    public string this[string key]
    {
        get { return (details.ContainsKey(key)) ? details[key] : null; }
    }

    public long DocumentId { get; set; }

    private Dictionary<string, string> details = new Dictionary<string, string>();
    public Dictionary<string, string> Details { get { return details; } }
}

I will need to bind these objects to a GridView, where I am dynamically setting up the columns to display.

My question is, how would I go about setting up my GridView to look to the indexer to pull its data (for example, if I wanted a column mapped to a value in the Details dictionary with the key of "DocumentName"):

BoundField bf = new BoundField();
bf.DataField = "DocumentName";
bf.HeaderText = "Document Name";

myGridView.Columns.Add(bf);

This won't work since "DocumentName" isn't a property of Document. I know if these columns were hard-coded, I could just use <%# Eval("[DocumentName]") %> on the page to get it to look to the indexer, but how do I go about doing this through the code?

Or am I forced to create a Template column, add in a label, and populate that on each row's creation?

Upvotes: 0

Views: 555

Answers (1)

Brian Mains
Brian Mains

Reputation: 50728

Yes, using the template as you suggested and populating from code-behind is one way. Other way is to programmably generate a DataTable object from the data provided, and bind that to the grid. That can be a usable solution sometimes too.

Upvotes: 1

Related Questions