2015-01-08 67 views
0

我有興趣讓用戶至少選中一個選項。有多少不重要,但至少有一個需要檢查。如果沒有,則需要生成錯誤。PowerShell .NET驗證至少一個複選框

有沒有辦法與GroupBox或其他類型的容器做到這一點?

代碼:

$groupBox1 = New-Object System.Windows.Forms.GroupBox 
$groupBox1.Location = New-Object System.Drawing.Point(8, 120) 
$groupBox1.Size = New-Object System.Drawing.Size(120, 144) 
$groupBox1.TabIndex = 0 
$groupBox1.TabStop = $false 
$groupBox1.Text = 'Options:' 

$checkBox1 = New-Object System.Windows.Forms.CheckBox 
$checkBox1.Location = New-Object System.Drawing.Point(8, 8) 
$checkBox1.TabIndex = 1 
$checkBox1.Text = 'Banana' 

$checkBox2 = New-Object System.Windows.Forms.CheckBox  
$checkBox2.Location = New-Object System.Drawing.Point(8, 40) 
$checkBox2.TabIndex = 2 
$checkBox2.Text = 'Apple' 

我發現了一些信息,但它是所有javascript

謝謝你的幫助。

if($checkBox1.Checked -or $checkBox2.Checked) { 
    #Continue work 
} 

什麼時候應該檢查:

完整的解決方案感謝佛羅多˚F:

$P21CheckBox1 = New-Object System.Windows.Forms.CheckBox 
$P21CheckBox1.Location = New-Object System.Drawing.Point(150, 150) 
$P21CheckBox1.AutoSize = $True 
$P21CheckBox1.TabIndex = 1 
$P21CheckBox1.Text = 'E-Mail notification' 
$P21CheckBox1.Add_CheckStateChanged({ 
    if($P21CheckBox1.Checked -or $P21CheckBox2.Checked) { 
     $P21Button1.Enabled = $True 
    } 
    else { 
     $P21Button1.Enabled = $False 
    } 
}) 
$P21.Controls.Add($P21CheckBox1) 

$P21CheckBox2 = New-Object System.Windows.Forms.CheckBox  
$P21CheckBox2.Location = New-Object System.Drawing.Point(150, 170) 
$P21CheckBox1.AutoSize = $True 
$P21CheckBox2.TabIndex = 2 
$P21CheckBox2.Text = 'Open the result' 
$P21CheckBox2.Add_CheckStateChanged({ 
    if($P21CheckBox1.Checked -or $P21CheckBox2.Checked) { 
     $P21Button1.Enabled = $True 
    } 
    else { 
     $P21Button1.Enabled = $False 
    } 
}) 
$P21.Controls.Add($P21CheckBox2) 


$P21Button1 = New-Object System.Windows.Forms.Button 
$P21Button1.Text = 'Execute' 
$P21Button1.TabIndex = 7 
$P21Button1.BackColor = $ButtonExecuteBackColor 
$P21Button1.Enabled = $False 
$P21Button1.add_Click(
    #Continue the work 
) 
$P21Button1.Location = $ButtonExecuteLocation 
$P21Button1.Size = $ButtonExecuteSize 
$P21.Controls.Add($P21Button1) 

回答

1

這是使用如果測試一樣容易呢?

  • 當你點擊一個按鈕?在按鈕的click-eventhandler中添加if-test。

  • 一個按鈕被禁用(灰色),直到檢查按鈕? 將if-test和啓用/禁用按鈕代碼添加到check-eventhandler複選框。

如果點擊一個按鈕時,該選項被選中,而你只想要生成錯誤,然後:

if(-not($checkBox1.Checked -or $checkBox2.Checked)) { 
    #Throw exception 
    Write-Error No checkboxes checked 

    #Error popup only 
    [System.Windows.Forms.MessageBox]::Show("Check minimum one checkbox!", 
            "ERROR", 
            [System.Windows.Forms.MessageBoxButtons]::OK, 
            [System.Windows.Forms.MessageBoxIcon]::Error) | Out-Null 
} 
+0

非常感謝您!這對我有很大的幫助:)我已經用你提供的完整解決方案更新了我的問題。真棒! – DarkLite1

相關問題