In the below section we will see how to add image and text inside the list box control.
Important points
- ImageList control: we will use this control as a data source of images.
- ListBox control: Inside this control, we will display image and text.
- DrawItem event of the listbox which we will use to set image into listbox.
Steps to add image and text inside list box control of win-form,
Step 1
Drag and drop two controls "List Box" and "Image List".
Step 2
Add images into "Image List" control.
Image List control -> Properties -> Images -> Collection.
Add images inside this collection and give a name to each added image.
Step 3
Create data table which will fill the list box data source.
- public DataTableGetTable() {
-
- DataTable table = new DataTable();
- table.Columns.Add("Id", typeof(int));
- table.Columns.Add("Data", typeof(string));
-
- table.Rows.Add(25, "Paint Data");
- table.Rows.Add(26, "Contact Data");
- table.Rows.Add(27, "find Data");
- table.Rows.Add(28, "Paint Data");
- table.Rows.Add(29, "Contact Data");
- table.Rows.Add(30, "find Data");
- return table;
- }
Step 4
Bind the List box with data table.
-
- lstBoxImageAndText.DataSource = GetTable();
- lstBoxImageAndText.DisplayMember = "Data";
- lstBoxImageAndText.ValueMember = "Id";
Step 5
User DrawItemevent of List Box to place an image with text data into Listbox.
Here, we will ImageList control to get the image,
- private void lstBoxImageAndText_DrawItem(object sender, DrawItemEventArgs e) {
-
- DataRowViewdrOfListBox = (DataRowView) lstBoxImageAndText.Items[e.Index];
- e.DrawBackground();
- Graphics g = e.Graphics;
- Rectangle rec = new Rectangle(e.Bounds.X, e.Bounds.Y, e.Bounds.Height, e.Bounds.Height);
-
-
-
- if (drOfListBox["Data"].ToString().Contains("Paint")) {
-
-
- g.DrawImage(imageList1.Images["Print"], rec);
- } else if (drOfListBox["Data"].ToString().Contains("Contact")) {
- g.DrawImage(imageList1.Images["Contact"], rec);
- } else if (drOfListBox["Data"].ToString().Contains("find")) {
- g.DrawImage(imageList1.Images["Search"], rec);
- }
-
- Point p = new Point(e.Bounds.X + e.Bounds.Height + 2, e.Bounds.Y + 3);
- e.Graphics.DrawString(drOfListBox["Data"].ToString(), e.Font, new SolidBrush(Color.Black), p);
- }