更新ComboBox选择项目后

时间:2016-03-22 21:10:36

标签: powershell powershell-v3.0

我迷路了,真的可以使用一些帮助。我正在尝试使用csv文件中的列名列表更新组合框(由打开文件按钮选择,字符串输入到文本框中)。

Function GetFileName($initialDirectory)
{
    [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null

    $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
    $OpenFileDialog.initialDirectory = $initialDirectory
    $OpenFileDialog.filter = "CSV (*.csv)| *.csv"
    $OpenFileDialog.multiselect = $false
    $OpenFileDialog.ShowDialog() | Out-Null
    return $OpenFileDialog.FileName
}

Function GetColumnsFromFile
{
    Param ($fileWithPath)

    [string]$csvFileColumnTitles = Get-Content $fileWithPath -totalcount 1

    [String[]]$csvFileColumnTitles = ($csvFileColumnTitles -replace ",", "|").Trim()
    [String[]]$csvFileColumnTitles = ($csvFileColumnTitles -replace "`"", "").Trim()
    [String[]]$listOfColumnTitles = $csvFileColumnTitles.Split('|',[System.StringSplitOptions]::RemoveEmptyEntries)

    return $listOfColumnTitles
}

Function GUIBox
{
    # Creates GUI Box In Memory
    [reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
    [reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
    Add-Type -AssemblyName System.Windows.Forms
    Add-Type -AssemblyName System.drawing
    $Form = New-Object system.Windows.Forms.Form
    $Form.Width = '1200'
    $Form.Height = '800'

    # TabControl
    $TabControl = New-Object System.Windows.Forms.TabControl
    $TabControl.Name = "TabControl"
    $TabControl.TabIndex = 4
    $TabControl.SelectedIndex = 0
    $TabControl.DataBindings.DefaultDataSourceUpdateMode = 0
    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 0
    $System_Drawing_Point.Y = 50
    $TabControl.Location = $System_Drawing_Point
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 685
    $System_Drawing_Size.Width = 1184
    $TabControl.Size = $System_Drawing_Size
    $Form.Controls.Add($TabControl)

    # Test 1 Tab
    $Test1_Tab = New-Object System.Windows.Forms.TabPage
    $Test1_Tab.DataBindings.DefaultDataSourceUpdateMode = 0
    $Test1_Tab.Name = "Test 1"
    $System_Drawing_Point = New-Object System.Drawing.Point
    $System_Drawing_Point.X = 0
    $System_Drawing_Point.Y = 50
    $Test1_Tab.Location = $System_Drawing_Point
    $System_Drawing_Size = New-Object System.Drawing.Size
    $System_Drawing_Size.Height = 685
    $System_Drawing_Size.Width = 1184
    $Test1_Tab.Size = $System_Drawing_Size
    $Test1_Tab.TabIndex = 1
    $Test1_Tab.Text = "Test 1"
    $Test1_Tab.UseVisualStyleBackColor = $True
    $TabControl.Controls.Add($Test1_Tab)

    # Open File Label
    $SelectSourceFile_Label = New-Object System.Windows.Forms.Label
    $SelectSourceFile_Label.Location = "10, 30"
    $SelectSourceFile_Label.Name = "label"
    $SelectSourceFile_Label.Size = "120, 20"
    $SelectSourceFile_Label.TabIndex = 3
    $SelectSourceFile_Label.Text = "Select Source File"
    $Test1_Tab.Controls.Add($SelectSourceFile_Label)

    # Open File Textbox
    $SelectSourceFile_Textbox = New-Object System.Windows.Forms.TextBox
    $SelectSourceFile_Textbox.Location = '10, 50'
    $SelectSourceFile_Textbox.Size = '200, 20'
    $SelectSourceFile_Textbox.TabIndex = 3
    $SelectSourceFile_Textbox.Text = $Test1_FileInput_Textbox_String
    $Test1_Tab.Controls.Add($SelectSourceFile_Textbox)

    # Open File Button
    $SelectSourceFile_Button = New-Object System.Windows.Forms.Button
    $SelectSourceFile_Button.DialogResult = 'None'
    $SelectSourceFile_Button.Location = '210, 50'
    $SelectSourceFile_Button.Name = 'Open File Button'
    $SelectSourceFile_Button.Size = '75, 25'
    $SelectSourceFile_Button.TabIndex = 3
    $SelectSourceFile_Button.Text = 'Open File'
    $SelectSourceFile_Button.UseVisualStyleBackColor = $true
    $SelectSourceFile_Button_Click = {$SelectSourceFile_Textbox.Text = GetFileName}
    $SelectSourceFile_Button.add_Click($SelectSourceFile_Button_Click)
    $Test1_Tab.Controls.Add($SelectSourceFile_Button)

    # Select Open File Columns Label
    $SelectSourceFileColumn_Label = New-Object System.Windows.Forms.Label
    $SelectSourceFileColumn_Label.Location = "10, 90"
    $SelectSourceFileColumn_Label.Name = "label"
    $SelectSourceFileColumn_Label.Size = "150, 20"
    $SelectSourceFileColumn_Label.TabIndex = 3
    $SelectSourceFileColumn_Label.Text = "Select Source File Column"
    $Test1_Tab.Controls.Add($SelectSourceFileColumn_Label)

    # Select Open File Columns Dropdown
    [String[]]$ColumnList = GetColumnsFromFile 'C:\Scripts\Tests\1Project\Test.csv'
    Write-Host '$ColumnList =' $ColumnList
    $SelectSourceFileColumn_Dropdown = New-Object 'System.Windows.Forms.ComboBox'
    $SelectSourceFileColumn_Dropdown.FormattingEnabled = $True
    $SelectSourceFileColumn_Dropdown.Location = '10, 110'
    $SelectSourceFileColumn_Dropdown.Name = 'File Column'
    $SelectSourceFileColumn_Dropdown.Size = '200, 20'
    $SelectSourceFileColumn_Dropdown.TabIndex = 3
    $SelectSourceFileColumn_Dropdown.Height = 30
    $Test1_Tab.Controls.Add($SelectSourceFileColumn_Dropdown)

    ## Display GUI Box ##
    $Form.ShowDialog()
}

GUIBox

csv文件......

"ColumnOne","ColumnTwo","ColumnThree"
"ColumnOneValueOne","ColumnTwoValueOne","ColumnThreeValueOne"
"ColumnOneValueTwo","ColumnTwoValueTwo","ColumnThreeValueTwo"
"ColumnOneValueThree","ColumnTwoValueThree","ColumnThreeValueThree"

因此在powershell窗口中,我们可以看到它能够打印3列名称。我知道如果我尝试这一行[String[]]$ColumnList = GetColumnsFromFile $SelectSourceFile_Textbox.Text(替换第110行),它将会出错(因为它会在用户有机会输入所选文件之前迭代这一行)。那么在用户输入csv文件后,如何更新组合框(带有csv文件中的列名)?

1 个答案:

答案 0 :(得分:1)

您可以这样做的一种方法是使用按钮点击显示FolderBrowserDialog,如果您从中获取文件名,请获取标题并将每个标题添加到组合框中。

当用户通过创建TextChanged事件键入文本框时,您可以使用相同的技术填充ComboBox。

ComboBox

我使用以下代码完成了这项工作:

function GUIBox {

    #----------------------------------------------
    #region Import the Assemblies
    #----------------------------------------------
    [void][reflection.assembly]::Load('System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
    [void][reflection.assembly]::Load('System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
    [void][reflection.assembly]::Load('System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
    [void][reflection.assembly]::Load('System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
    [void][reflection.assembly]::Load('System.ServiceProcess, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
    #endregion Import Assemblies

    #----------------------------------------------
    #region Generated Form Objects
    #----------------------------------------------
    [System.Windows.Forms.Application]::EnableVisualStyles()
    $form1 = New-Object 'System.Windows.Forms.Form'
    $textbox1 = New-Object 'System.Windows.Forms.TextBox'
    $combobox1 = New-Object 'System.Windows.Forms.ComboBox'
    $buttonLoadCsv = New-Object 'System.Windows.Forms.Button'
    $InitialFormWindowState = New-Object 'System.Windows.Forms.FormWindowState'
    #endregion Generated Form Objects

    #----------------------------------------------
    # User Generated Script
    #----------------------------------------------

    function Get-FileName($initialDirectory)
    {
        [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null

        $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
        $OpenFileDialog.initialDirectory = $initialDirectory
        $OpenFileDialog.filter = "CSV (*.csv)| *.csv"
        $OpenFileDialog.multiselect = $false
        $OpenFileDialog.ShowDialog() | Out-Null
        return $OpenFileDialog.FileName
    }

    $form1_Load={
        #TODO: Initialize Form Controls here

    }

    $buttonLoadCsv_Click={
        #TODO: Place custom script here

        $file = Get-FileName -initialDirectory $env:USERPROFILE

        if ($file)
        {
            $textbox1.Text = $file

            try
            {
                $headers = Import-Csv -Path $file | Get-Member | Where-Object -FilterScript {$_.MemberType -eq 'NoteProperty'} | Select-Object -ExpandProperty Name -Unique
                Write-Host ($headers | Out-String)
                $combobox1.Items.Clear()
                foreach($header in $headers)
                {
                    $combobox1.Items.Add($header)
                }
            }
            catch
            {
                Write-Warning -Message "The following error occured while trying to get the headings for csv file $file`: $($_.Exception.Message)"
            }
        }
    }

    # --End User Generated Script--
    #----------------------------------------------
    #region Generated Events
    #----------------------------------------------

    $Form_StateCorrection_Load=
    {
        #Correct the initial state of the form to prevent the .Net maximized form issue
        $form1.WindowState = $InitialFormWindowState
    }

    $Form_Cleanup_FormClosed=
    {
        #Remove all event handlers from the controls
        try
        {
            $buttonLoadCsv.remove_Click($buttonLoadCsv_Click)
            $form1.remove_Load($form1_Load)
            $form1.remove_Load($Form_StateCorrection_Load)
            $form1.remove_FormClosed($Form_Cleanup_FormClosed)
        }
        catch [Exception]
        { }
    }
    #endregion Generated Events

    #----------------------------------------------
    #region Generated Form Code
    #----------------------------------------------
    $form1.SuspendLayout()
    #
    # form1
    #
    $form1.Controls.Add($textbox1)
    $form1.Controls.Add($combobox1)
    $form1.Controls.Add($buttonLoadCsv)
    $form1.ClientSize = '390, 76'
    $form1.Name = 'form1'
    $form1.Text = 'Form'
    $form1.add_Load($form1_Load)
    #
    # textbox1
    #
    $textbox1.Location = '12, 14'
    $textbox1.Name = 'textbox1'
    $textbox1.Size = '284, 20'
    $textbox1.TabIndex = 2
    #
    # combobox1
    #
    $combobox1.DropDownStyle = 'DropDownList'
    $combobox1.FormattingEnabled = $True
    $combobox1.Location = '12, 40'
    $combobox1.Name = 'combobox1'
    $combobox1.Size = '284, 21'
    $combobox1.TabIndex = 1
    #
    # buttonLoadCsv
    #
    $buttonLoadCsv.Location = '302, 12'
    $buttonLoadCsv.Name = 'buttonLoadCsv'
    $buttonLoadCsv.Size = '75, 49'
    $buttonLoadCsv.TabIndex = 0
    $buttonLoadCsv.Text = 'Load Csv'
    $buttonLoadCsv.UseVisualStyleBackColor = $True
    $buttonLoadCsv.add_Click($buttonLoadCsv_Click)
    $form1.ResumeLayout()
    #endregion Generated Form Code

    #----------------------------------------------

    #Save the initial state of the form
    $InitialFormWindowState = $form1.WindowState
    #Init the OnLoad event to correct the initial state of the form
    $form1.add_Load($Form_StateCorrection_Load)
    #Clean up the control events
    $form1.add_FormClosed($Form_Cleanup_FormClosed)
    #Show the Form
    return $form1.ShowDialog()

} #End Function

#Call the form
GUIBox | Out-Null