如何在精简框架中循环浏览列表框的选定项

本文关键字:列表 浏览 循环 框架 | 更新日期: 2023-09-27 18:36:33

我从这里改编了以下代码

foreach (String table in tablesToTouch)
{
    foreach (Object selecteditem in listBoxSitesWithFetchedData.SelectedItems)
    {
        site = selecteditem as String;
        hhsdbutils.DeleteSiteRecordsFromTable(site, table);
    }
}

。但是,唉,SelectedItems 成员对我来说似乎不可用:"'System.Windows.Forms.ListBox' 不包含 'SelectedItems' 的定义,并且找不到接受类型为'System.Windows.Forms.ListBox' 的第一个参数的扩展方法'SelectedItems'(您是否缺少 using 指令或程序集引用?)"

另一个建议是:

foreach(ListItem listItem in listBox1.Items)
{
   if (listItem.Selected == True)
   {
     . . .

。但我也没有可用的列表项。

完成相同操作的解决方法是什么?

更新

我至少可以做两件(有点笨拙的)事情:

0) Manually keep track of items selected in listBoxSitesWithFetchedData (as they are clicked) and loop through *that* list
1) Dynamically create checkboxes instead of adding items to the ListBox (getting rid of the ListBox altogether), and use the text value of checked checkboxes to pass to the "Delete" method

但我仍然认为必须有比这些更直接的方法。

更新 2

我可以这样做(它编译):

foreach (var item in listBoxSitesWithFetchedData.Items)
{
    hhsdbutils.DeleteSiteRecordsFromTable(item.ToString(), table);
}

。但我仍然面临仅对已选择的项目采取行动的问题。

更新 3

由于 CF-Whisperer 说在 CF(楔形文字)的阴暗迷宫世界中不可能实现列表框多选,我将代码简化为:

foreach (String table in tablesToTouch)
{
    // Comment from the steamed coder:
    // The esteemed user will have to perform this operation multiple times if they want 
to delete from multiple sites              
    hhsdbutils.DeleteSiteRecordsFromTable(listBoxSitesWithFetchedData.SelectedItem.ToString(), 
        table);
}

如何在精简框架中循环浏览列表框的选定项

紧凑

框架Listbox只包含一个object项的列表。 它调用每个ToString()进行显示,但项目在那里。

因此,假设我们有一个对象:

class Thing
{
    public string A { get; set; }
    public int B { get; set; }
    public Thing(string a, int b)
    {
        A = a;
        B = b;
    }
    public override string ToString()
    {
        return string.Format("{0}: {1}", B, A);
    }
}

我们把一些扔进一个ListBox

listBox1.Items.Add(new Thing("One", 1));
listBox1.Items.Add(new Thing("Two", 2));
listBox1.Items.Add(new Thing("Three", 3));

它们将在列表中显示为ToString()等效项(例如"一:1")。

您仍然可以通过如下所示的强制转换或as操作将它们作为源对象进行迭代:

foreach (var item in listBox1.Items)
{
    Console.WriteLine("A: " + (item as Thing).A);
    Console.WriteLine("B: " + (item as Thing).A);
}