萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

C# CheckedListBox 移動勾選項目 (另一版本:單向複製不刪除來源)

前言

延續上一篇,此版本示範「複製勾選項目到目標列表,來源保留」的邏輯,適用於「加入購物車」、「加入待處理清單」等場景。

程式碼範例

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);
            }
        }
    }
}

搭配 CheckedIndices 高效寫法

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` 直接回傳勾選項目的索引集合,避免遍歷所有項目。

若需移動 (Cut) 而非複製

請參考上一篇「反向迴圈」或「收集物件再移除」寫法。

UI 體驗小建議

  • 加入「全選/取消全選」按鈕:`for (int i=0; i
  • 雙擊項目切換勾選:處理 `MouseDoubleClick` 事件,`clb.SetItemChecked(index, !clb.GetItemChecked(index))`。
  • 資料繫結模式:請操作 `DataSource` 底層集合的 `IsChecked` 屬性,UI 會自動同步。
copyright © 萬盛學電腦網 all rights reserved