[英]removing selected items from a checked list box
我寫了一個代碼,將第一個清單列表框中的選定項目轉移到另一個清單列表框中。這部分代碼有效(但是我仍然必須找到一種方法,以使相同的選定項目不會一遍又一遍地寫)。我的第二個目標是從第一個復選框列表中刪除選定的項目。 我得到的錯誤是數組超出范圍。
private void button_ekle_Click(object sender, EventArgs e)
{
int i = 0;
int k = 0;
i = clb_input.Items.Count;
//the number of items in the first checkedlistbox
for (k = 0; k <i; k++)
{
if (clb_input.GetItemChecked(k) == true)
{
//clb_output is the second checkedlistbox
clb_output.Items.Add(clb_input.Items[k]);
clb_input.Items.Remove(clb_input.CheckedItems[k]);
i--;
}
else { }
}
}
您的問題是由於在CheckedItems集合上使用索引器k引起的。
CheckedItems集合的元素數可能少於Items集合的計數,因此索引器的值可能不包含在CheckedItems集合中。
但是,當您需要這種代碼時,通常會反轉循環。
從頭開始,朝頭走
private void button_ekle_Click(object sender, EventArgs e)
{
for (int k = clb_input.Items.Count - 1; k >= 0; k--)
{
if (clb_input.GetItemChecked(k) == true)
{
clb_output.Items.Add(clb_input.Items[k]);
// Remove from the Items collection, not from the CheckedItems collection
clb_input.Items.RemoveAt(k);
}
else { }
}
}
您還應該記住,當您希望使用傳統的for循環遍歷一個集合時,您的限制索引值是項目數減去1,因為NET中的每個集合都從索引0開始。因此,如果您有一個包含10個項目的集合有效索引為0到9。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.