muttley91
muttley91

Reputation: 12674

Populate a ListView with Strings

I'm a bit new to ASP.NET, so bear with me. I came across this solution which would allow me to add an array of strings to a ListView as a row of data. However, I'm not sure on the proper way to set it up. In just trying this solution with a ListView I dropped onto my website, I'm told that new ListViewItem() requires a parameter of type ListViewItemType. The sample solution doesn't provide that, so is it different in ASP.NET?

So the main question I'm asking is: If I have an array of strings, how can I add that to a ListView as a row of data in ASP.NET?

EDIT: I'd like to make sure I'm asking for the right control. I was under the impression a ListView was something like this (but in ASP.NET), but what I'm getting so far is not. It's just a line of text.

Upvotes: 3

Views: 6381

Answers (2)

Win
Win

Reputation: 62260

If you want to display like in the example, you want to use GridView instead of ListView.

String collection is not enough to display in multiple columns. You need a collection of objects.

Screen Shot (top is ListView, bottom is GridView)

enter image description here

Sample Code

<asp:ListView runat="server" ID="ListView1">
    <ItemTemplate>
        <%# Eval("Name") %>, 
        <%# Eval("Email") %>, 
        <%# Eval("Phone") %><br />
    </ItemTemplate>
</asp:ListView>
<br/>
<asp:GridView ID="GridView1" AutoGenerateColumns="True" runat="server" />

public class User
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
}

protected void Page_Load(object sender, EventArgs e)
{
    var collections = new List<User>
        {
            new User {Name = "Jon Doe", Email = "[email protected]", Phone = "123-123-1234"},
            new User {Name = "Marry Doe", Email = "[email protected]", Phone = "456-456-4567"},
            new User {Name = "Eric Newton", Email = "[email protected]", Phone = "789-789-7890"},
        };

    ListView1.DataSource = collections;
    ListView1.DataBind();

    GridView1.DataSource = collections;
    GridView1.DataBind();
}

Upvotes: 2

Aghilas Yakoub
Aghilas Yakoub

Reputation: 28970

You can convert your array to list with ToList operator

c#

lv.DataSource = yourArray.ToList();
lv.DataBind();

asp.net

<asp:ListView ID="lv" runat="server">

        <ItemTemplate>
            <asp:Label ID="lbl" runat="server" Text='<%# Container.DataItem %>'/>
        </ItemTemplate>

</asp:ListView>

Upvotes: 1

Related Questions