如何:响应 Windows 窗体 CheckBox 的单击
每当用户单击某 Windows 窗体 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 控件确定操作的进程。
单击复选框时确定操作的进程
使用 case 语句查询 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。
请参见
任务
如何:使用 Windows 窗体 CheckBox 控件设置选项