[英]how can I know which Item was selected in listview + imagelist
This is the fist time I post a question on this site and I need some help. 这是我第一次在此网站上发布问题,我需要一些帮助。 This is my code
这是我的代码
private void loadMatrixOfTables()
{
try
{
var tb = BaSic.db.tb_Tables; //load database with LINQ
lsvTables.Clear(); //this is my lisview
foreach (var b in tb)
{
if (b.Status == true)
{
lsvTables.Items.Add(b.Name,1);
}
else
{
lsvTables.Items.Add(b.Name, 0);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.ToString());
}
}
My table has 2 fields: id and name What I need do to get item value, not item text. 我的表有2个字段:id和name我需要做什么来获取项目值,而不是项目文本。
I don't know the type of b so the example is using the 2 known attributes id and string assuming that are an int and a string respectively . 我不知道b的类型,所以该示例使用2个已知属性id和string,分别假设它们是int和string。 Just change them for your containing class.
只需将它们更改为您的包含类。
First you need to create your own ListViewItem, to support show the name on the listView and get his id when is required. 首先,您需要创建自己的ListViewItem,以支持在listView上显示名称并在需要时获取其ID 。 In your case it looks like this:
在您的情况下,它看起来像这样:
public class CustomListViewItem : ListViewItem
{
public CustomListViewItem(int id, string name)
{
Id = id;
Name = name;
}
public int Id { get; set; }
public string Name { get; set; }
}
Using it 使用它
First create your item 首先创建您的物品
var item = new CustomListViewItem(id, name)
To show in the listview the name just add: 要在列表视图中显示名称,只需添加:
item.Text = name
and then added to the listView: 然后添加到listView中:
lsvTables.Items.Add(item,1)
To retrieve the selected item's id just cast the selected item as CustomListViewItem. 要检索所选项目的ID,只需将所选项目转换为CustomListViewItem。 For example:
例如:
int id = (CustomListViewItem)lsvTables.SelectedItems[0].Id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.