combobox control to allow dynamic width of longest item

Ask questions about creating Graphical User Interfaces (GUI) in PowerShell and using WinForms controls.
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
This topic is 5 years and 9 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked
User avatar
joeypiccola
Posts: 9
Last visit: Mon Jun 18, 2018 7:44 am

combobox control to allow dynamic width of longest item

Post by joeypiccola »

Hello,

I have a form with limited layout space for things like super wide comboboxes. That said, I have a combobox that I'd like to have the DropDownList width fit to the widest item in the data collection. Is this possible?

I realize I could simply make the combobox's width larger but 1) I'm trying to keep things visually looking nice and 2) the combobox's collection I'm trying to accommodate is actually sourced on form load from a dynamic json file (refreshed nightly).

Image

Thanks for the help,
Joey
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: combobox control to allow dynamic width of longest item

Post by jvierra »

There is really no facility in Forms to do what you ask. You would have to custom code this and adjust the position of all items around the ComboBox.
User avatar
davidc
Posts: 5913
Last visit: Mon Jul 08, 2019 8:55 am
Been upvoted: 2 times

Re: combobox control to allow dynamic width of longest item

Post by davidc »

Here is an example on now how to do this in C#:

https://stackoverflow.com/questions/484 ... xs-content
David
SAPIEN Technologies, Inc.
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: combobox control to allow dynamic width of longest item

Post by jvierra »

Here is a quick example of the conversion.

Code: Select all

$form1_Load={
    $names = (dir).Fullname
    $maxlength = ($names|select -expand length |Measure-Object -Maximum).Maximum
    $lbl = [System.Windows.Forms.Label]::New()
    $lbl.Text = 'X'*$maxlength
    $combobox1.DropdownWidth = $lbl.PreferredWidth
    $combobox1.Items.AddRange($names)
}
There is a more reliable way using "DrawItem" but it takes more code.
This topic is 5 years and 9 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked