How to set the Height of the Elements present in the ListBox in C#?
Last Updated :
17 Jul, 2019
In Windows Forms, ListBox control is used to show multiple elements in a list, from which a user can select one or more elements and the elements are generally displayed in multiple columns. In ListBox, you can set the height of the elements present in the ListBox using the ItemHeight Property of the ListBox. The maximum height of the ListBox item is 255 pixels. You can set this property in two different ways:
1. Design-Time: It is the easiest way to set the height of the elements present in the ListBox as shown in the following steps:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the height of the elements present in the ListBox control programmatically with the help of given syntax:
public virtual int ItemHeight { get; set; }
Here, the value of this property is of System.Int32 type. The height of the element is always considered in pixels. It will throw an ArgumentOutOfRangeException if the value of this property was set to less than 0 or more than 255 pixels. The following steps show how to set the height of the elements present in the ListBox dynamically:
- Step 1: Create a list box using the ListBox() constructor is provided by the ListBox class.
// Creating ListBox using ListBox class constructor
ListBox lstbox = new ListBox();
- Step 2: After creating ListBox, set the ItemHeight Property of the ListBox provided by the ListBox class.
// Setting the height of the items
lstbox.ItemHeight = 13;
- Step 3: And last add this ListBox control to the form using Add() method.
// Add this ListBox to the form
this.Controls.Add(lstbox);
Example:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp28 {
public partial class Form1 : Form {
public Form1()
{
InitializeComponent();
}
private void Form1_Load( object sender, EventArgs e)
{
Label lb = new Label();
lb.Location = new Point(243, 80);
lb.Text = "Select post" ;
this .Controls.Add(lb);
ListBox lstbox = new ListBox();
lstbox.Location = new Point(246, 104);
lstbox.ItemHeight = 13;
lstbox.Items.Add( "Intern" );
lstbox.Items.Add( "Software Engineer" );
lstbox.Items.Add( "Project Manager" );
lstbox.Items.Add( "HR" );
this .Controls.Add(lstbox);
}
}
}
|
Output:
Share your thoughts in the comments
Please Login to comment...