Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display a list of user controls in ASP.NET WebForms

This is not really a question so I hope don't be fired! So I have to make a twitter like timeline, a superposition of blocks containing informations.

I really don't know how to make this.. The problem is the number of blocks aren't the same each time, sometimes it will be 1 block only, sometimes two or sometimes more..

So do I make some HtmlWriter to write the html directly? I pretty new in asp.net so maybe it is possible to do that more easily! With WebUserControl maybe, a block = a wuc so I can add the number of wuc I need.. I'm quite lost so maybe somebody have done this kind of thing already and can put me on the right way..

Thank you for reading!

like image 361
bAN Avatar asked Feb 16 '11 08:02

bAN


1 Answers

You are on a right track with creating a usercontrol to represent a "block", but what you're lacking is a mechanism to show them as a list.

ASP.NET has many possible solutions for this, but the simplest one would be to use a ListView control.

It's hard to provide example code without knowing what your data looks like, but let's assume you have a class called Block:

public class Block
{
    public string Title {get; set;}
    public string Text { get; set; }
}

To display one block, you would create a user control, let's call it BlockControl:

Markup:

<div style="margin:10px; padding:10px; background:#eee;">
    <h2><%= Block.Title %></h2>
    <%= Block.Text %>
</div>

Code-behind:

public partial class BlockControl : System.Web.UI.UserControl
{
    //Note the public property, we'll use this to data bind the ListView's item to the user control
    public Block Block { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {
    }
}

Then, in your .aspx page you can declare an ASP.NET ListView control, and use BlockControl in the ListView's ItemTemplate to present the data. Notice how we bind the ListView's current data item to the BlockControl.Block property.

<asp:ListView ID="BlockList" runat="server">
    <ItemTemplate>
        <uc:BlockControl Block="<%# Container.DataItem %>" runat="server" />
    </ItemTemplate>
</asp:ListView>            

From the .aspx code-behind you set the ListView data source. In your case the data probably comes from a database, but here it's just some mock data:

protected void Page_Load(object sender, EventArgs e)
{
    List<Block> blocks = new List<Block>
    {
        new Block { Title = "Block1", Text="This is the block 1 content"},
        new Block { Title = "Block2", Text="This is the block 2 content"}
    };

    this.BlockList.DataSource = blocks;
    this.BlockList.DataBind();
}

Now you have the presentation of a single block encapsulated in a user control, and the ListView provides you with the mechanism to display a variable number of these user controls based on your data.

like image 65
jevakallio Avatar answered Oct 15 '22 09:10

jevakallio