【问题标题】:Searching a ListBox where Items have customised data搜索项具有自定义数据的列表框
【发布时间】:2015-07-30 09:46:53
【问题描述】:

我正在将数据加载到带有附加日期时间数据的列表框中。现在我想在列表框中搜索包含 tagID 的项目(例如:e2003450976543)。当我搜索列表框时,即使我可以看到它,我也找不到 tagID。我假设搜索参数不排除附加的 DateTime 数据。这是我的代码:

class ExpiringItem
{
    private string text;
    public ExpiringItem(string text)
    {
        this.text = text;
        this.Added = DateTime.Now;
    }
    public DateTime Added { get; private set; }
    public override string ToString()
    {
        return text;
    }
}

private void timer1_Tick(object sender, EventArgs e)
{
    for (int i = listBox1.Items.Count -1; i > -1; i--)
    {
        var exp = (ExpiringItem)listBox1.Items[i];
        var timeVisible = DateTime.Now - exp.Added;
        if (timeVisible.TotalSeconds > 30)
            listBox1.Items.RemoveAt(i);

    }
}

插入我正在使用:lstTagsHold.Items.Add(new ExpiringItem(txtTagID.Text));

基本上我要做的就是检查tagID 是否存在于列表框中...

对于我正在使用的测试:if (lstHold.Items.Contains(TagID))..

【问题讨论】:

  • 我看不到你在哪里检查tagID ..?
  • 我正在使用:if (lstHold.Items.Contains(TagID)) {

标签: c# search listbox


【解决方案1】:

Items.Contains 方法使用存储在 ListBox.Items 中的对象测试参数的 identity。但是由于您没有对象而只有一个字符串值,所以它无法工作,因此您需要搜索 Items..:

按照 J.C. 的说明创建 text public 后,您可以在这样的函数中访问它:

int findFirstID(ListBox lb, string id)
{
    for (int i = 0; i < lb.Items.Count; i++)
    {
        var ei = lb.Items[i] as ExpiringItem;
        // if text is public:
        if (ei.text == id) return i;
        // if it isn't:
        if (ei.ToString()== id) return i;

    }
    return -1;
}

这将返回具有您搜索的 ID 的第一个项目的索引,如果未找到,则返回 -1。

如果您只想检查是否在listBox 中,您可以使用一点LINQ

// if text is public:
if (listBox1.Items.Cast<ExpiringItem>().Where(x => x.text == yourID).Count() > 0) ..

// if it isn't::
if (listBox1.Items.Cast<ExpiringItem>().Where(x => x.ToString()== yourID).Count() > 0) ..

【讨论】:

  • 我想我有一个金发的时刻或一整天。这是我得到的错误: Error 26 'MT.Compcrete.frmMain.ExpiringItem.text' is inaccessible due to its protection level G:\Current Software Dev\1 AT Race Timing System\22A 07.15 Standalone\Client\frmMain.cs 1577 90 客户端 我怎样才能让它公开和可访问?
  • 正如在两个答案和错误消息中指出的那样:您需要使文本字段以另一种方式公开,否则您无法从外部访问它。 或者您可以更改代码以使用您已有的ToString() 方法。我会改变答案..
  • 好的,所以我已将属性更改为:public string text;。然后运行此代码: if (listBox1.Items.Cast().Where(x => x.text == TagID).Count() > 0) { MessageBox.Show("Item found"); }
  • 但它说无法将“System.String”类型的对象转换为“ExpiringItem”类型
  • 已排序。我让它运行起来。感谢大家的帮助。
【解决方案2】:

我猜你的代码中的 tagID 等于 this.text

您需要知道 ListBox 不包含字符串列表,而是对象列表。您可以看到 tagID,因为您已覆盖 ToString() 方法来呈现文本。

根据var exp = (ExpiringItem)listBox1.Items[i];,exp.text 应该是你的tagID,但它是private。请为它写一个公共属性,你的tagID就在那里。

【讨论】:

  • 我试过了:string serTag = (ExpiringItem)listBox1.Items[g].ToString();但这会产生错误
  • string serTag = ( (ExpiringItem)listBox1.Items[g] ).ToString(); 怎么样?
猜你喜欢
  • 1970-01-01
  • 2013-04-03
  • 2023-03-09
  • 2013-12-21
  • 1970-01-01
  • 1970-01-01
  • 2018-12-13
  • 2022-12-14
  • 1970-01-01
相关资源
最近更新 更多