【问题标题】:how can I know which Item was selected in listview + imagelist我如何知道在 listview + imagelist 中选择了哪个项目
【发布时间】:2014-12-08 17:39:25
【问题描述】:

这是我第一次在这个网站上发布问题,我需要一些帮助。 这是我的代码

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());
    }
}

我的表有 2 个字段:id 和 name 我需要做什么来获取项目值,而不是项目文本。

【问题讨论】:

  • 您在寻找SelectedIndexChanged 吗?
  • 我的表有 2 列:id 和 name。

标签: c# winforms listview selecteditem imagelist


【解决方案1】:

我不知道 b 的类型,所以该示例使用 2 个已知属性 id 和 string 假设它们分别是 int 和 string。只需为您的包含类更改它们。

首先你需要创建自己的ListViewItem,以支持在listView上显示name,并在需要时获取他的id。在您的情况下,它看起来像这样:

public class CustomListViewItem : ListViewItem
{
    public CustomListViewItem(int id,  string name)
    {
        Id = id;
        Name = name;
    }

    public int Id { get; set; }
    public string Name { get; set; }
}

使用它

首先创建你的项目

var item = new CustomListViewItem(id, name)

要在列表视图中显示名称,只需添加:

item.Text = name

然后添加到listView中:

lsvTables.Items.Add(item,1)

要检索所选项目的 id,只需将所选项目转换为 CustomListViewItem。例如:

int id = (CustomListViewItem)lsvTables.SelectedItems[0].Id;

【讨论】:

  • 很高兴为您提供帮助。如果您好心,请接受我的回答。
猜你喜欢
  • 2012-09-07
  • 1970-01-01
  • 2013-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多