我从here
改编了以下代码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可用。
完成同样事情的解决方法是什么?
我至少可以做两件事(有点kludgy):
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
但我仍然认为必须采用比那些更直接的方式。
我可以这样做(它编译):
foreach (var item in listBoxSitesWithFetchedData.Items)
{
hhsdbutils.DeleteSiteRecordsFromTable(item.ToString(), table);
}
...但我仍然只能处理已经选择的项目。
由于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);
}
答案 0 :(得分:1)
Compact Framework 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()
等效词(例如" One:1")。
你仍然可以通过这样的强制转换或as
操作迭代它们作为源对象:
foreach (var item in listBox1.Items)
{
Console.WriteLine("A: " + (item as Thing).A);
Console.WriteLine("B: " + (item as Thing).A);
}