我在选项卡中有一个列表框,其中列出了数据库中的内容。问题是如何使用选定的文本。
通常我会使用$result = $form.ShowDialog()
但我尝试过$result = $tab.ShowDialog()
并收到错误“方法调用失败,因为 [System.Windows.Forms.TabPage] 不包含‘ShowDialog’”。
有没有办法从选项卡中的列表框中进行选择?
答案1
在我看来,从表单或选项卡中选择列表框项之间没有真正的区别。在下面的代码中,将控件添加到表单和选项卡控件后,单击会将OK
列表框(来自 Tab1)中的选定项显示到另一个选项卡(Tab2)。
通过 来从列表框中选择项目$listBox.SelectedItem
。
Function selectButton_Click()
{
$item = $listBox.SelectedItem
$Resultlabel.Text = "The selected item is: $item"
$TabControl.SelectedTab = $Tab2
}
Function closeButton_Click()
{
$form.Close()
}
function myForm
{
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$form = New-Object System.Windows.Forms.Form
$form.Text = 'Continents'
$form.Size = New-Object System.Drawing.Size(250,250)
$form.StartPosition = 'CenterScreen'
$selectButton = New-Object System.Windows.Forms.Button
$selectButton.Location = New-Object System.Drawing.Point(20,150)
$selectButton.Size = New-Object System.Drawing.Size(75,23)
$selectButton.Text = 'OK'
$selectButton.Add_Click({selectButton_Click})
# Create tabControl and Tabs
$TabControl = New-object System.Windows.Forms.TabControl
$Tab1 = New-Object System.Windows.Forms.TabPage
$Tab1.Text = 'Tab1'
$Tab2 = New-Object System.Windows.Forms.TabPage
$Tab2.Text = 'Tab2'
#Tab Control
$tabControl.Location = New-Object System.Drawing.Point(0,0)
$tabControl.Name = "tabControl"
$tabControl.Size= New-Object System.Drawing.Size(180,200)
$form.Controls.Add($tabControl)
$tabControl.Controls.Add($Tab1)
$tabControl.Controls.Add($Tab2)
$Tab1.Controls.Add($selectButton)
$closeButton = New-Object System.Windows.Forms.Button
$closeButton.Location = New-Object System.Drawing.Point(100,150)
$closeButton.Size = New-Object System.Drawing.Size(75,23)
$closeButton.Text = 'Close'
$closeButton.Add_Click({closeButton_Click})
$Tab1.Controls.Add($closeButton)
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(20,20)
$label.Size = New-Object System.Drawing.Size(280,20)
$label.Text = 'Select a continent:'
$Tab1.Controls.Add($label)
$Resultlabel = New-Object System.Windows.Forms.Label
$Resultlabel.Location = New-Object System.Drawing.Point(20,20)
$Resultlabel.Size = New-Object System.Drawing.Size(200,20)
$Resultlabel.Text = 'The selected item is:'
$Tab2.Controls.Add($Resultlabel)
$listBox = New-Object System.Windows.Forms.ListBox
$listBox.Location = New-Object System.Drawing.Point(10,50)
$listBox.Size = New-Object System.Drawing.Size(100,20)
$listBox.Height = 80
[void] $listBox.Items.Add('Africa')
[void] $listBox.Items.Add('America')
[void] $listBox.Items.Add('Asia')
[void] $listBox.Items.Add('Europe')
[void] $listBox.Items.Add('Oceania')
$Tab1.Controls.Add($listBox)
$form.ShowDialog()
}
myForm