Google Reviews
If you find this content or our services useful, please leave us a review.

Creating a combobox in Powershell and adding an item to it is a relatively trivial task:

$combobox = New-Object System.Windows.Forms.ComboBox

The text of the selected combobox can be obtained like so:


This is a combobox in its most simplistic form. The trouble is, I’m from an ASP.Net background and it’s often handy to bind a value (the hidden reference to the selected item – usually a primary key integer) AND some text (the value that the user sees in the combobox – the ‘friendly’ name).  This requires a bit more leg work to implement and can be done by using a datatable, adding data to the datatable, and binding this datatable to our combobox like so:


#create a form
$form = New-Object System.Windows.Forms.Form

#create a datatable to bind to our combobox
$datatable = New-Object system.Data.DataTable
#Define Columns
$col1 = New-Object system.Data.DataColumn "Value",([string])
$col2 = New-Object system.Data.DataColumn "Text",([string])

#add columns to datatable
#Create a row
$datarow1 = $datatable.NewRow()

#Enter data in the row
$datarow1.Value = "Example Value 1"
$datarow1.Text = "Example Text 1"

#Add the row to the datatable

#Create another row
$datarow2 = $datatable.NewRow()

#Enter data in the row
$datarow2.Value = "Example Value 2"
$datarow2.Text = "Example Text 2"

#Add the row to the datatable

#create a combobox
$combobox = New-Object System.Windows.Forms.ComboBox		
		#output the selected value and text
		write-host $combobox.SelectedItem["Value"] $combobox.SelectedItem["Text"]

#clear combo before we bind it

#bind combobox to datatable
$combobox.ValueMember = "Value"
$combobox.DisplayMember = "Text"
$combobox.Datasource = $datatable

#add combobox to form

#show form
Using Powershell to Databind a Combobox with a Value and some Text

1 thought on “Using Powershell to Databind a Combobox with a Value and some Text

  1. If I wanted to select a value other than the first value entered, without rearranging the values, how would I do this?

Comments have now been disabled. If you have a question to ask about this post please ask the community!