【发布时间】:2015-01-08 05:30:33
【问题描述】:
我创建了一个带有组合框的简单 Windows 表单,我试图用我的 csv 中的全名列填充它,我希望它返回变量中的缩写名称列值,所以我使用了一个哈希表并添加了两个列,但是从组合框中选择一个项目后, $namehash[$return] 为空。它不应该返回缩写名称吗?我在 c# 和 VB 中找到了使用 Combobox.DisplayMember、Combobox.ValueMember、Combobox.DataSource 的其他示例。我如何在 powershell 中做到这一点?
我的 csv 用逗号分隔
姓名、简称
密歇根州
俄亥俄州
Import-Module Activedirectory
function button ($WF) {
###################Load Assembly for creating form & button######
[void][System.Reflection.Assembly]::LoadWithPartialName( “System.Windows.Forms”)
[void][System.Reflection.Assembly]::LoadWithPartialName( “Microsoft.VisualBasic”)
#####Define the form size & placement
$form = New-Object “System.Windows.Forms.Form”;
$form.Width = 500;
$form.Height = 190;
$form.Text = $title;
$form.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen;
$form.ControlBox = $True
##############Define text label2
$textLabel2 = New-Object “System.Windows.Forms.Label”;
$textLabel2.Left = 25;
$textLabel2.Top = 80;
$textLabel2.Text = $WF;
############Define text box2 for input
$cBox2 = New-Object “System.Windows.Forms.combobox”;
$cBox2.Left = 150;
$cBox2.Top = 80;
$cBox2.width = 200;
###############"Add descriptions to combo box"##############
$NameHash = @{}
import-csv 'C:\temp\test_cidb.csv' | ForEach-Object {
$cBox2.Items.Add($_.Description)
$NameHash.Add($_.Name,$_.Shortname)
}
############Define text box3 for input
#############Define default values for the input boxes
$defaultValue = “”
$cBox2.Text = $defaultValue;
#############define OK button
$button = New-Object “System.Windows.Forms.Button”;
$button.Left = 360;
$button.Top = 45;
$button.Width = 100;
$button.Text = “Ok”;
$Button.Cursor = [System.Windows.Forms.Cursors]::Hand
$Button.Font = New-Object System.Drawing.Font("Times New Roman",12,[System.Drawing.FontStyle]::BOLD)
############# This is when you have to close the form after getting values
$eventHandler = [System.EventHandler]{
$cBox2.Text;
$form.Close();};
$button.Add_Click($eventHandler) ;
#############Add controls to all the above objects defined
$form.Controls.Add($button);
$form.Controls.Add($textLabel2);
$form.Controls.Add($cBox2);
$ret = $form.ShowDialog();
#################return values
return $cbox2.text
}
$return= button “Job Descriptions"
我通过使用它作为数据源创建数据表并使用显示成员、值成员、数据源类绑定组合框来解决了我自己的问题。
$reader = new-object System.IO.StreamReader($csvfile)
$line = $reader.ReadLine()
$columns = $line.Split($csvdelimiter)
foreach ($column in $columns) {$null = $datatable.Columns.Add($column) }
while (($line = $reader.ReadLine()) -ne $null) {
$row = $datatable.NewRow()
$row.itemarray = $line.Split($csvdelimiter)
$datatable.Rows.Add($row)
}
$cbox2.DisplayMember = "Name"
$cbox2.ValueMember = "Shortname"
$cbox2.DataSource = $datatable
$States=cbox2.SelectedValue
【问题讨论】:
-
你的 csv 是什么样的?可以复制标题和第一行吗?
标签: powershell csv combobox bind