手动将项目插入ListView控件

时间:2013-03-14 20:29:30

标签: c# asp.net listview

我搜索了S / O和Google,但我无法解决这个问题(大部分搜索结果都是从数据源填充Listview)。我想根据用户选择手动将项目添加到listview控件。

ListView listView1 = new ListView();
listView1.Items.Add(lstAuthors[i]);  

我收到错误:
最佳重载方法匹配' System.Collections.Generic.ICollection.Add(System.Web.UI.WebControls.ListViewDataItem)'有一些无效的论点

导致错误的原因是什么?

1 个答案:

答案 0 :(得分:7)

此错误仅表示lstAuthors[i]不是System.Web.UI.WebControls.ListViewDataItem(这是ListView.Items.Add函数的唯一有效参数。

为了按照现在的方式执行此操作,您需要initialize a ListViewDataItem,并为dataIndex参数使用虚拟值(因为您没有基础索引数据源):< / p>

ListViewDataItem newItem = new ListViewDataItem(dataIndex, displayIndex);

说实话,这似乎不是使用ListView控件的正确方法。也许你可以告诉我们你想要完成什么,我们可以帮助你采用另一种方法。


这是一个非常简洁的基本方法,可以做你想做的事情。您基本上维护通用List<T>作为数据源,并将 绑定到您的ListView。这样您就可以处理维护ListView内容的所有细节,但仍然可以使用数据绑定的内置功能。<​​/ p>

基本标记(一个ListView,其中包含一个项目的ItemTemplate,一个用于选择项目的DropDownList,以及一个用于将这些项目添加到ListView的按钮):

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:ListView ID="ListView1" runat="server">
        <ItemTemplate>
            <div>
                <asp:Label ID="AuthorNameLbl" runat="server" Text='<%# Eval("AuthorName") %>'></asp:Label>
            </div>
        </ItemTemplate>
    </asp:ListView>
    <br />
    <asp:DropDownList ID="DropDownList1" runat="server">
        <asp:ListItem>Stephen King</asp:ListItem>
        <asp:ListItem>Mary Shelley</asp:ListItem>
        <asp:ListItem>Dean Koontz</asp:ListItem>
    </asp:DropDownList>
    <br />
    <br />
    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</asp:Content>

代码隐藏:

// Honestly, this string  just helps me avoid typos when 
// referencing the session variable
string authorKey = "authors";

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        // If the session variable is empty, initialize an 
        // empty list as the datasource
        if (Session[authorKey] == null)
        {
            Session[authorKey] = new List<Author>();
        }
        BindList();
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    // Grab the current list from the session and add the 
    // currently selected DropDown item to it.
    List<Author> authors = (List<Author>)Session[authorKey];
    authors.Add(new Author(DropDownList1.SelectedValue));
    BindList();
}

private void BindList()
{
    ListView1.DataSource = (List<Author>)Session[authorKey];
    ListView1.DataBind();
}

// Basic author object, used for databinding
private class Author
{
    public String AuthorName { get; set; }

    public Author(string name)
    {
        AuthorName = name;
    }
}
相关问题