2016-03-22 4 views
0

Я потерян и действительно могу использовать некоторую помощь. Я пытаюсь обновить поле со списком со списком имен столбцов из файла csv (выбранного кнопкой открытого файла и ввода строки в текстовое поле).Обновление ComboBox Как только элемент выбран

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), она будет ошибочной (потому что она будет проходить через эту строку, прежде чем пользователь сможет ввести выбранный файл). Итак, как мне обновить combobox (с именами столбцов из файла csv) после ввода пользователем своего файла csv?

ответ

1

Один из способов сделать это - использовать кнопку, чтобы показать FolderBrowserDialog, и если вы получите имя файла из него, получите заголовки и добавьте их в выпадающий список.

Вы можете использовать ту же технику для заполнения ComboBox, когда пользователь вводит текстовое поле, создавая событие TextChanged.

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 
+0

Совершенного Спасибо :) –

Смежные вопросы