延續上一篇,此版本示範「複製勾選項目到目標列表,來源保留」的邏輯,適用於「加入購物車」、「加入待處理清單」等場景。
private void btnCopyChecked_Click(object sender, EventArgs e)
{
int total = checkedListBoxSource.Items.Count;
for (int i = 0; i < total; i++)
{
if (checkedListBoxSource.GetItemChecked(i))
{
string text = checkedListBoxSource.GetItemText(checkedListBoxSource.Items[i]);
// 避免重複加入 (以文字比較)
if (!checkedListBoxTarget.Items.Contains(text))
{
checkedListBoxTarget.Items.Add(text);
}
}
}
}
private void btnCopyChecked_Click(object sender, EventArgs e)
{
foreach (int idx in checkedListBoxSource.CheckedIndices)
{
string text = checkedListBoxSource.GetItemText(checkedListBoxSource.Items[idx]);
if (!checkedListBoxTarget.Items.Contains(text))
checkedListBoxTarget.Items.Add(text);
}
}
`CheckedIndices` 直接回傳勾選項目的索引集合,避免遍歷所有項目。
請參考上一篇「反向迴圈」或「收集物件再移除」寫法。