Reputation: 459
I have a Dictionary (let's call it info) that I am trying to bind to a DataList (we'll call it directory). The dictionary is declared as follows:
Dictionary<string, string> info = new Dictionary<string, string>(){
{"AdvertisementID", "1"},
{"CompanyName", "Test"},
//More elements
};
Now, I bind the Dictionary to the DataList as follows:
directory.DataSource = info;
directory.DataBind();
My asp code looks like this:
<asp:DataList ID = "directory" runat="server" RepeatColums="3" RepeatDirection="Horizontal" DataKeyField="Key">
<ItemTemplate>
//HTML Formatting
<%# DataBinder.Eval(Container.DataItem, "CompanyName") %>
</ItemTemplate>
</asp:DataList>
For whatever reason, "CompanyName" cannot be found. When outputting Container.DataItem.ToString(), all that appears is AdvertisementID (the first thing in the dictionary). What am I doing incorrectly?
EDIT: I want to also mention that I've attempted implementing this solution to no avail: Binding DataList to Dictionary
EDIT 2: What I am trying to accomplish is the following:
I have a bunch of information that I pulled from a database in a Dictionary. This dictionary is set up like Dictionary, both as strings. And I am trying to output this info to a webpage.
EDIT 3 Using the solution below (Binding a list of objects instead of a dictionary), my asp code still cannot find the property "CompanyName". The object and all of the Strings within it appear in the DataItem in the debugger.
Upvotes: 1
Views: 2200
Reputation: 68440
You cannot use the Dictionary like that. Items on dictionary are KeyValuePair
and only available properties are Key
and Value
.
So, the only 2 valid options would be
<%# DataBinder.Eval(Container.DataItem, "Key") %>
Or
<%# DataBinder.Eval(Container.DataItem, "Value") %>
You may want to explain better what you're trying to achieve since it's possible that this is not enough for solving your problem.
EDIT
You would normally have something like tis
public class Info
{
public int AdvertisementID { get; set; }
public string CompanyName { get; set; }
//More elements
}
And then
IList<Info> infoList = GetList();
directory.DataSource = infoList;
directory.DataBind();
You can keep your html as it is if you implement something like this
Upvotes: 3
Reputation: 19656
Try using Key
and Value
instead.
(Value
instead of CompanyName)
Upvotes: 0