C# 在列表视图中选择一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12596500/
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
Select a row in listview
提问by ankur
I am web developer , working on a part of my project developed in WinForms. So my question could be a basic one. Try to bear with it.
我是 Web 开发人员,从事我在 WinForms 中开发的项目的一部分。所以我的问题可能是一个基本的问题。试着忍受它。
I have two list views on my page and a remove button that works for both.
我的页面上有两个列表视图和一个适用于两者的删除按钮。
Problems.
问题。
- I am not able to select a row in both the list view when I run my program, may be some property needed for it?
- If I am able to select the row I want to detect which list view item has been selected, so how would I do that?
I have three columns and have bound the data by using the code below.
listView1.Columns.Add("ID",20); listView1.Columns.Add("Name",40); listView1.Columns.Add("Mobile",40); foreach (var item in dataList) { newItem = new ListViewItem(); newItem.SubItems.Add(item.ID.ToString()); newItem.SubItems.Add(item.Name); newItem.SubItems.Add(item.Mobile.ToString()); listView1.Items.Add(newItem); }
- 当我运行我的程序时,我无法在两个列表视图中选择一行,可能需要一些属性吗?
- 如果我能够选择行,我想检测已选择哪个列表视图项,那么我该怎么做?
我有三列,并使用下面的代码绑定了数据。
listView1.Columns.Add("ID",20); listView1.Columns.Add("Name",40); listView1.Columns.Add("Mobile",40); foreach (var item in dataList) { newItem = new ListViewItem(); newItem.SubItems.Add(item.ID.ToString()); newItem.SubItems.Add(item.Name); newItem.SubItems.Add(item.Mobile.ToString()); listView1.Items.Add(newItem); }
but the IDcolumn is left blank and the data starts to bind in these sense.
但该ID列留空,数据开始在这些意义上绑定。
ID Name Mobile
1 abc
2 xyz
So how do I properly show the data?
那么如何正确显示数据呢?
- Lastly I want to use my
IDcolumn to delete the data. So if I givewidth=0, is this the best way to hide a column?
- 最后我想用我的
ID列来删除数据。所以如果我给width=0,这是隐藏列的最佳方式吗?
采纳答案by Dennis
- See ListView.FullRowSelectproperty.
- See ListView.SelectedItemsproperty. Note, that by default
ListViewallows multiselection. - Set item text via constructor:
newItem = new ListViewItem(item.ID.ToString());, then add rest of subitems (except ofitem.ID). - If you want to delete the column, just remove it from the columns collection.
- 请参阅ListView.FullRowSelect属性。
- 请参阅ListView.SelectedItems属性。请注意,默认情况下
ListView允许多选。 - 通过构造函数设置项目文本:
newItem = new ListViewItem(item.ID.ToString());,然后添加其余的子项目(除了item.ID)。 - 如果要删除该列,只需将其从列集合中删除即可。

