0

我从这里改编了以下代码

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'的定义,并且没有扩展方法'SelectedItems'接受'System.'类型的第一个参数。可以找到 Windows.Forms.ListBox'(您是否缺少 using 指令或程序集引用?)

另一个建议是:

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

...但我也没有可用的 ListItem。

完成相同事情的解决方法是什么?

更新

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

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

1 回答 1

1

Compact FrameworkListbox只包含一个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);
}
于 2015-01-06T21:43:13.790 回答