0

如何检查我的列表框中是否选择了某个项目?所以我有一个按钮删除,但我只希望在列表框中选择一个项目时执行该按钮。我在 C# 后面使用 asp.net 代码。如果此验证发生在服务器端,我更愿意。

干杯..

4

6 回答 6

1

在按钮单击的回调中,只需检查列表框的选定索引是否大于或等于零。

protected void removeButton_Click( object sender, EventArgs e )
{
    if (listBox.SelectedIndex >= 0)
    {
        listBox.Items.RemoveAt( listBox.SelectedIndex );
    }
}
于 2008-11-07T03:28:04.513 回答
1

实际上, SelectedIndex 是从零开始的,因此您的检查必须是:

if (listBox.SelectedIndex >= 0) ...

于 2008-11-07T03:49:31.943 回答
1

要删除多个项目,您需要反向解析这些项​​目。

protected void removeButton_Click(object sender, EventArgs e)
{
    for (int i = listBox.Items.Count - 1; i >= 0; i--)
        listBox.Items.RemoveAt(i);
}

如果你像往常一样解析,那么结果将是非常出乎意料的。例如:如果您删除第 0 项,则第 1 项将成为新的第 0 项。如果您现在尝试删除您认为是第 1 项的内容,您实际上会删除您所看到的第 2 项。

于 2008-11-07T08:23:34.073 回答
0

您可能希望根据您的 prob desc 以及ListBox.SelectedIndex 如果未选择任何内容将返回 -1的事实采用早期突破方法。

所以借用一些 tvanfosson 的按钮事件处理程序代码。

protected void removeButton_Click( object sender, EventArgs e )
{
    if (listBox.SelectedIndex < 0) { return; }
    // do whatever you wish to here to remove the list item 
}
于 2008-11-07T04:27:34.660 回答
0

要从集合中删除项目,您需要向后循环。

for (int i=lbSrc.Items.Count - 1, i>=0, i--)
{
   //code to check the selected state and remove the item
}
于 2008-11-07T08:22:24.263 回答
-1
for (int i = 0; i < lbSrc.Items.Count; i++)
{
    if (lbSrc.Items[i].Selected == true)
    {
        lbSrc.Items.RemoveAt(lbSrc.SelectedIndex);
    }
}

这就是我想出的。

于 2008-11-07T07:52:36.400 回答