Dev527
Dev527

Reputation: 47

How to set height of a list box to match the number of elements in it using C#?

I am creating desktop application using C# and I want to set height of list Box with respect to number of elements in it. For example in picture below,

enter image description here

I have four elements in list it should show all the four at once but it is showing only two. I want to change height randomly on the base of number of elements in it. Any one can help me with this?

Upvotes: 1

Views: 2164

Answers (1)

user12031933
user12031933

Reputation:

You can write:

listBox1.Height = listBox1.ItemHeight * (listBox1.Items.Count + 1);

Also you can set a maximum limit to protect the form:

int count = listBox1.Items.Count + 1;
if ( count > 20 ) count = 20;
listBox1.Height = listBox1.ItemHeight * count;

Also you can use a maximum height or any other check instead of items count:

int height = listBox1.ItemHeight * count;
if ( height > 300 ) height = 300; 
listBox1.Height = height;

The ItemHeight depends on the font size.

Upvotes: 3

Related Questions