如何:回應 Windows Form CheckBox 按一下動作
每當使用者按一下 Windows Forms CheckBox 控制項時,就會發生 Click 事件。 您可以根據核取方塊的狀態,將應用程式程式設計為執行某些動作。
若要回應 CheckBox 點選
在 Click 事件處理常式中,使用 Checked 屬性來判斷控制項的狀態,並執行任何必要的動作。
Private Sub CheckBox1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles CheckBox1.Click ' The CheckBox control's Text property is changed each time the ' control is clicked, indicating a checked or unchecked state. If CheckBox1.Checked = True Then CheckBox1.Text = "Checked" Else CheckBox1.Text = "Unchecked" End If End Sub
private void checkBox1_Click(object sender, System.EventArgs e) { // The CheckBox control's Text property is changed each time the // control is clicked, indicating a checked or unchecked state. if (checkBox1.Checked) { checkBox1.Text = "Checked"; } else { checkBox1.Text = "Unchecked"; } }
private: void checkBox1_CheckedChanged(System::Object ^ sender, System::EventArgs ^ e) { if (checkBox1->Checked) { checkBox1->Text = "Checked"; } else { checkBox1->Text = "Unchecked"; } }
您也可以使用 CheckBox 控制項來判斷動作的過程。
若要判斷按一下核取方塊時的動作
使用大小寫陳述式來查詢 CheckState 屬性的值,以判斷動作的過程。 當 ThreeState 屬性設定為
true
時,CheckState 屬性可能會傳回三個可能的值,代表正在核取的方塊、未核取的方塊,或以灰色外觀顯示該方塊的第三個不確定狀態,以表示選項無法使用。Private Sub CheckBox1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles CheckBox1.Click Select Case CheckBox1.CheckState Case CheckState.Checked ' Code for checked state. Case CheckState.Unchecked ' Code for unchecked state. Case CheckState.Indeterminate ' Code for indeterminate state. End Select End Sub
private void checkBox1_Click(object sender, System.EventArgs e) { switch(checkBox1.CheckState) { case CheckState.Checked: // Code for checked state. break; case CheckState.Unchecked: // Code for unchecked state. break; case CheckState.Indeterminate: // Code for indeterminate state. break; } }
private: void checkBox1_CheckedChanged(System::Object ^ sender, System::EventArgs ^ e) { switch(checkBox1->CheckState) { case CheckState::Checked: // Code for checked state. break; case CheckState::Unchecked: // Code for unchecked state. break; case CheckState::Indeterminate: // Code for indeterminate state. break; } }
注意
當 ThreeState 屬性設定為
true
時,Checked 屬性會針對 Checked 和 Indeterminate 傳回true
。