using System;
using System.Windows.Forms;
namespace CheckedListBoxSample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Init();
}
private void Init()
{
btnAddFruit.Enabled = false;
btnShow.Enabled = false;
btnReset.Enabled = false;
checkedListBox1.Items.Clear();
listBox1.Items.Clear();
// 預設新增資料
string[] myFruit = { "Apples", "Oranges", "Tomato" };
checkedListBox1.Items.AddRange(myFruit);
checkedListBox1.Items.Add("Grape", true);
// 預設為 false,先點選該項目後,才能勾選 CheckBox,開啟後就可以直接點選
checkedListBox1.CheckOnClick = true;
// 只支援 None 和 One,不支援 MultiSimple 和 MultiExtended
// 使用 None 情況下就完全無法點選,One 為預設值
checkedListBox1.SelectionMode = SelectionMode.One;
}
private void txtAddFruit_TextChanged(object sender, EventArgs e)
{
// 有輸入文字才能新增
btnAddFruit.Enabled = string.IsNullOrWhiteSpace(txtAddFruit.Text) == false;
}
private void btnAddFruit_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(txtAddFruit.Text))
return;
if (checkedListBox1.CheckedItems.Contains(txtAddFruit.Text))
return;
// 新增後清空
checkedListBox1.Items.Add(txtAddFruit.Text, CheckState.Checked);
txtAddFruit.Text = string.Empty;
}
private void btnShow_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
btnReset.Enabled = false;
for (int i = 0; i < checkedListBox1.CheckedItems.Count; i++)
{
listBox1.Items.Add(checkedListBox1.CheckedItems[i]);
}
if (listBox1.Items.Count > 0)
btnReset.Enabled = true;
}
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (e.NewValue == CheckState.Unchecked)
{
// 點擊當下的 CheckBox = Checked 控件數量,判斷是否為最後一個 Checked
if (checkedListBox1.CheckedItems.Count == 1)
{
btnShow.Enabled = false;
}
}
else
{
btnShow.Enabled = true;
}
}
private void btnReset_Click(object sender, EventArgs e)
{
Init();
}
}
}
星期三, 8月 03, 2022
[C#] CheckedListBox
根據官方文章 - CheckedListBox 的簡易筆記文
沒有留言:
張貼留言