3

私はS/Oとグーグルを検索しましたが、これを理解することはできません(ほとんどの検索結果はデー​​タソースからリストビューに入力されています)。ユーザーの選択に基づいて、リストビューコントロールにアイテムを手動で追加したい。

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

エラーが発生します:
「System.Collections.Generic.ICollection.Add(System.Web.UI.WebControls.ListViewDataItem)」に最も一致するオーバーロードされたメソッドにいくつかの無効な引数があります

エラーの原因は何ですか?

4

1 に答える 1

7

このエラーは、それが(関数の唯一の有効なパラメーターである)でlstAuthors[i]はないことを単に意味します。System.Web.UI.WebControls.ListViewDataItemListView.Items.Add

これを現在の方法で行うには、ListViewDataItemを初期化し、dataIndexパラメーターにダミー値を使用する必要があります(基になるインデックス付きデータソースがないため)。

ListViewDataItem newItem = new ListViewDataItem(dataIndex, displayIndex);

正直なところ、これは実際にはListViewコントロールを使用する正しい方法のようには思えません。たぶん、あなたが達成しようとしていることを私たちに教えてくれるかもしれませんし、私たちは別のアプローチを手伝うことができます。


これは、あなたがやりたいことをするための本当に簡素化された基本的なアプローチです。基本的に、データソースとしてジェネリックList<T>を維持し、それをにバインドますListView。このようにして、ListViewのコンテンツを維持するためのすべての詳細を処理できますが、データバインディングの組み込みの機能を引き続き使用できます。

基本的なマークアップ(ItemTemplateに1つのアイテムを含むListView、アイテムを選択するための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;
    }
}
于 2013-03-14T20:55:34.963 に答える