@bobnoordam

Binding fields at runtime to a datalist

The ASP.NET datalist can be bound to a datasource if you have one, but for real flexability you may want to bind the code at runtime. This sample shows how to bind the datalist at runtime using Linq. The list consists of a number of links, to which both the url and the description will be bound from the code.

While this method may at first seem more work, you will quickly find that manual binding provides much more flexibility in where you get your data from, and handling any preprocessing you may need. Especialy when making changes later the maintenance cost will be much lower if you arent tightly coupled to a dataset.

<asp:DataList ID="DataList1" runat="server" RepeatColumns="1">
    <ItemTemplate>
        <a href="<%#DataBinder.Eval(Container.DataItem, "LinkUrl")%>">
            <%#DataBinder.Eval(Container.DataItem, "LinkName") %>
        </a>      
    </ItemTemplate>            
</asp:DataList>

Now the data for this can basicaly come from anywhere (usualy a database), but for this sample we will simply bind to a list of predefined records containing the description and the link. Replace at your convinience and scenario.

private class LinkData {
    public string LinkUrl { get; set; }
    public string LinkName { get; set; }
}

So we need a bit of code to setup a few records, and bind them to the list. The essential part is this:

List<LinkData> sampleData = new List<LinkData>();
sampleData.Add(new LinkData() {
    LinkUrl = "http://www.google.com",
    LinkName = "Google"
});
sampleData.Add(new LinkData() {
    LinkUrl = "http://www.bing.com",
    LinkName = "Bing"
});
//
// Bind the data to the list
DataList1.DataSource = sampleData;
DataList1.DataBind();

With the boilerplate handling of the page load, we finaly arrive at the full sample, which still is quite small

#region Init

protected void Page_Load(object sender, EventArgs e) {
    if (!IsPostBack) {
        BindData();
    }
}

#endregion

#region Procedures

private void BindData() {
    List<LinkData> sampleData = new List<LinkData>();
    sampleData.Add(new LinkData() {
        LinkUrl = "http://www.google.com",
        LinkName = "Google"
    });
    sampleData.Add(new LinkData() {
        LinkUrl = "http://www.bing.com",
        LinkName = "Bing"
    });
    //
    // Bind the data to the list
    DataList1.DataSource = sampleData;
    DataList1.DataBind();
}

#endregion

#region Nested type: LinkData

private class LinkData {
    public string LinkUrl { get; set; }
    public string LinkName { get; set; }
}

#end