チェックボックスは、通常「Checkされている」「Checkされていない」の2つの
状態を持ちます。
しかし、場合によってはこのどちらでもない、第3の状態を持たせたい場合があります。
これを、Indeterminateな状態といいます。具体的には、チェックボックスに薄い色でチェックマークがついている状態です。
これを実現するのは簡単です。CheckBoxのThreeStateプロパティをtrueにします。
状態を取得するには、Checkedではなく、CheckStateプロパティを使います。
なお、ThreeStateプロパティがtrueなチェックボックスでは、クリックするたびに、「Checked」「Indeterminate」「Unchecked」の順で変化します。
public CheckState CheckState { get; set; }
プロパティ値のCheckState列挙体のメンバと意味は次の通りです。
| メンバ | 意味 | 
|---|---|
| Checked | チェックされている | 
| Indeterminate | 不確定状態 | 
| Unchecked | チェックされていない | 
では、サンプルのプログラムを見てみましょう。
// threestate01.cs
using System;
using System.Drawing;
using System.Windows.Forms;
class threestate01 : Form
{
    public static void Main()
    {
        string[] str = new string[3] { "Check0", "Check1", "Check2" };
        threestate01 form = new threestate01();
        form.Padding = new Padding(10);
        MyCheck[] mc = new MyCheck[3];
        for (int i = 2; i >= 0; i--)
        {
            mc[i] = new MyCheck(str[i]);
            form.Controls.Add(mc[i]);
        }
        Label label = new Label();
        label.Parent = form;
        label.BackColor = SystemColors.Control;
        label.Dock = DockStyle.Bottom;
        label.TextAlign = ContentAlignment.MiddleLeft;
        
        Application.Run(form);
    }
    public threestate01()
    {
        Text = "猫でもわかるC#プログラミング";
        BackColor = SystemColors.Window;
    }
}
class MyCheck : CheckBox
{
    public MyCheck(string str)
    {
        Text = str;
        BackColor = SystemColors.Control;
        ThreeState = true;
        Dock = DockStyle.Top;
        Margin = new Padding(10);
        CheckStateChanged += new EventHandler(MyCheck_CheckStateChanged);
    }
    void MyCheck_CheckStateChanged(object sender, EventArgs e)
    {
        CheckBox cb = (CheckBox)sender;
        string str = cb.CheckState.ToString();
        cb.Parent.Controls[3].Text = cb.Text + "が「" + str + "」に変化しました";
    }
}
ThreeStateプロパティがtrueのチェックボックスでは、状態が変化するとCheckStateChangedイベントが発生します。実行結果は、次のようになります。
状態の変化したチェックボックスが、ラベルに表示されます。
Update 22/Nov/2006 By Y.Kumei