我该如何检查一个项目是否在我的列表框中被选中? 所以我有一个按钮删除,但我只想要该按钮执行,如果在列表框中选择一个项目。即时通讯使用C#后面的asp.net代码。我宁愿如果这个验证发生在服务器端。listbox验证
欢呼声..
我该如何检查一个项目是否在我的列表框中被选中? 所以我有一个按钮删除,但我只想要该按钮执行,如果在列表框中选择一个项目。即时通讯使用C#后面的asp.net代码。我宁愿如果这个验证发生在服务器端。listbox验证
欢呼声..
for (int i = 0; i < lbSrc.Items.Count; i++)
{
if (lbSrc.Items[i].Selected == true)
{
lbSrc.Items.RemoveAt(lbSrc.SelectedIndex);
}
}
这是我想出了。
在回调按钮点击,只需检查列表框的选择指数大于或等于零。
protected void removeButton_Click(object sender, EventArgs e)
{
if (listBox.SelectedIndex >= 0)
{
listBox.Items.RemoveAt(listBox.SelectedIndex);
}
}
其实,SelectedIndex的是从零开始,你的支票必须是:
如果(listBox.SelectedIndex> = 0) ...
您可能希望去的早期突破的方法根据您的概率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
}
要从集合中删除项目,您需要向后循环。
for (int i=lbSrc.Items.Count - 1, i>=0, i--)
{
//code to check the selected state and remove the item
}
要删除多个项目,您需要解析相反的项目。
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项
与修正@ jons911观察。 – tvanfosson 2008-11-07 03:50:31