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

Actually, this is not a question, so I hope they do not fire him! So I have to do a Twitter, like a timeline, a superposition of blocks containing information.

I really don’t know how to do it .. The problem is that the number of blocks is not the same every time, sometimes it will be only one block, sometimes two or sometimes more.

So can I get HtmlWriter to write html directly? I am new to asp.net, so maybe this can be made easier! Perhaps using WebUserControl, block = a wuc, so I can add the wuc number I need. I was completely lost, so maybe someone has already done this already and may direct me on the right path.

Thanks for reading!

+5
source share
1 answer

You are on the right track with creating a usercontrol to represent the "block", but what you are missing is a mechanism showing them as a list.

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

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

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

To display a single block, you must create a custom control, call it BlockControl:

Markup:

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

Code for:

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

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

.aspx ListView ASP.NET BlockControl ListView ItemTemplate . , ListView BlockControl.Block.

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

.aspx- ListView. , , , :

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();
}

, , ListView .

+10

All Articles