2008-11-07 29 views
0

我該如何檢查一個項目是否在我的列表框中被選中? 所以我有一個按鈕刪除,但我只想要該按鈕執行,如果在列表框中選擇一個項目。即時通訊使用C#後面的asp.net代碼。我寧願如果這個驗證發生在服務器端。listbox驗證

歡呼聲..

回答

-1
for (int i = 0; i < lbSrc.Items.Count; i++) 
{ 
    if (lbSrc.Items[i].Selected == true) 
    { 
     lbSrc.Items.RemoveAt(lbSrc.SelectedIndex); 
    } 
} 

這是我想出了。

1

在回調按鈕點擊,只需檢查列表框的選擇指數大於或等於零。

protected void removeButton_Click(object sender, EventArgs e) 
{ 
    if (listBox.SelectedIndex >= 0) 
    { 
     listBox.Items.RemoveAt(listBox.SelectedIndex); 
    } 
} 
+0

與修正@ jons911觀察。 – tvanfosson 2008-11-07 03:50:31

1

其實,SelectedIndex的是從零開始,你的支票必須是:

如果(listBox.SelectedIndex> = 0) ...

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 
} 
0

要從集合中刪除項目,您需要向後循環。

for (int i=lbSrc.Items.Count - 1, i>=0, i--) 
{ 
    //code to check the selected state and remove the item 
} 
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項