C# 如何在 Listview 中显示列表项?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9935931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 11:17:26  来源:igfitidea点击:

How to display List items in Listview?

c#asp.net

提问by Bramble

I have a ListView in my aspx file like this:

我的 aspx 文件中有一个 ListView,如下所示:

<asp:ListView ID="ListView1" runat="server"></asp:ListView>

and then I have List like this:

然后我有这样的列表:

List<string> mylist = new List<string>();

Im trying to populate the ListView like so:

我试图像这样填充 ListView:

foreach(string elem in mylist)
{
  ListView1.Items.Add(new ListViewItem(elem));
}

But my compiler is telling me best overload match error & cannot convert string to ListViewItem. This is a asp.net 4.0 web app. Any suggestions?

但是我的编译器告诉我最好的重载匹配错误并且无法将字符串转换为 ListViewItem。这是一个 ASP.NET 4.0 网络应用程序。有什么建议?

采纳答案by KodeKreachor

Try binding your ListView like the following:

尝试像下面这样绑定你的 ListView:

code-behind

代码隐藏

List<string> mylist = new List<string>() { "stealthy", "ninja", "panda"};
listView.DataSource = mylist;
listView.DataBind();

aspx

aspx

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

回答by Metro Smurf

With a ListView, you should be able to bind the data to the DataSourceof the control:

使用ListView,您应该能够将数据绑定到DataSource控件的 :

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

回答by John Weldon

ListViewItemdoes not have any constructor that takes a string. Also ListView.Itemsis an IList<ListViewDataItem>not a collection of ListViewItem

ListViewItem没有任何接受字符串的构造函数。此外ListView.ItemsIList<ListViewDataItem>不是一个集合ListViewItem

You probably want to use databinding rather than iteratively adding items anyway.

您可能想要使用数据绑定而不是迭代添加项目。