Getsuyodev, Programming is mainly used when constructing an application. Programming requires knowledge of application domains, algorithms, and programming language expertise. Programming can be developed in different logic based on developer knowledge.

C# ListBox Control



The ListBox control enables you to display a list of items to the user that the user can select by clicking.

Setting ListBox Properties

You can set ListBox properties by using Properties Window. To get Properties window, you can Press F4 or by right-clicking on a control to get the “Properties” menu item.

You can set property values in the right side column of the property window.

C# Listbox example

Add Items in a Listbox

Syntax

public int Add (object item);

In addition to display and selection functionality, the ListBox also provides features that enable you to add items to the ListBox efficiently and to find text within the items of the list. You can use the Add or Insert method to add items to a list box. The Add method adds new items at the end of an unsorted list box.

listBox1.Items.Add("Sunday");

If the Sorted property of the C# ListBox is set to true, the item is inserted into the list alphabetically. Otherwise, the item is inserted at the end of the ListBox.

Insert Items in a Listbox

Syntax

public void Insert (int index, object item);

You can inserts an item into the list box at the specified index.

listBox1.Items.Insert(0, "First");
listBox1.Items.Insert(1, "Second");
listBox1.Items.Insert(2, "Third");
listBox1.Items.Insert(3, "Forth");

Listbox Selected Item

If you want to retrieve a single selected item to a variable , use the following code.

string item = listBox1.GetItemText(listBox1.SelectedItem);

Or you can use

string item = listBox1.SelectedItem.ToString();

Or

string item= listBox1.Text;

Selecting Multiple Items from Listbox

The SelectionMode property determines how many items in the list can be selected at a time. A ListBox control can provide single or multiple selections using the SelectionMode property. If you change the selection mode property to multiple select, then you will retrieve a collection of items from ListBox1.SelectedItems property.

listBox1.SelectionMode = SelectionMode.MultiSimple;

The ListBox class has two SelectionMode. Multiple or Extended.

In Multiple modes, you can select or deselect any item in a ListBox by clicking it. In Extended mode, you need to hold down the Ctrl key to select additional items or the Shift key to select a range of items.

The following C# program initially fills seven days in a week while in the form load event and set the selection mode property to MultiSimple. At the Button click event, it will display the selected items.

using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }
    private void Form1_Load(object sender, EventArgs e)
    {
      listBox1.Items.Add("Sunday");
      listBox1.Items.Add("Monday");
      listBox1.Items.Add("Tuesday");
      listBox1.Items.Add("Wednesday");
      listBox1.Items.Add("Thursday");
      listBox1.Items.Add("Friday");
      listBox1.Items.Add("Saturday");
      listBox1.SelectionMode = SelectionMode.MultiSimple;
    }
    private void button1_Click(object sender, EventArgs e)
    {
      foreach (Object obj in listBox1.SelectedItems )
      {
        MessageBox.Show(obj.ToString ());
      }
    }
  }
}

Getting All Items from the List box

The Items collection of C# Winforms Listbox returns a Collection type of Object so you can use ToString() on each item to display its text value as below:

private void button1_Click_1(object sender, EventArgs e)
{
  string items = "";
  foreach (var item in listBox1.Items)
  {
    items += item.ToString() + ", ";
  }
  MessageBox.Show(items);
}

How to bind a ListBox to a List?

You can bind a List to a ListBox control by creating a new List Object and add items to the List.

Creating a List

List<string> nList = new List<string>();
nList.Add("January");
nList.Add("February");
nList.Add("March");
nList.Add("April");

Binding to List

The next step is to bind this List to the Listbox. In order to do that you should set datasource of the Listbox.

listBox1.DataSource = nList;
private void button1_Click(object sender, EventArgs e)
{
  List<string> nList = new List<string>();
  nList.Add("January");
  nList.Add("February");
  nList.Add("March");
  nList.Add("April");
  listBox1.DataSource = nList;
}

How to bind a Listbox to database values?

First of all, you could create a connection string and fetch data from a database to a Dataset.

connetionString = "Data Source=ServerName;Initial Catalog=databasename;User ID=userid;Password=yourpassword";
sql = "select au_id,au_lname from authors";

Set Datasource for ListBox

Next step is that you have set Listbox datasource as Dataset.

listBox1.DataSource = ds.Tables[0];
listBox1.ValueMember = "au_id";
listBox1.DisplayMember = "au_lname";
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
      string connetionString = null;
      SqlConnection connection;
      SqlCommand command;
      SqlDataAdapter adapter = new SqlDataAdapter();
      DataSet ds = new DataSet();
      int i = 0;
      string sql = null;
      //connetionString = "Data Source=ServerName;Initial Catalog=databasename;User ID=userid;Password=yourpassword";
      //sql = "select au_id,au_lname from authors";
      connection = new SqlConnection(connetionString);
      try
      {
        connection.Open();
        command = new SqlCommand(sql, connection);
        adapter.SelectCommand = command;
        adapter.Fill(ds);
        adapter.Dispose();
        command.Dispose();
        connection.Close();
        listBox1.DataSource = ds.Tables[0];
        listBox1.ValueMember = "au_id";
        listBox1.DisplayMember = "au_lname";
      }
      catch (Exception ex)
      {
        MessageBox.Show("Cannot open connection ! ");
      }
    }
  }
}

How to refresh DataSource of a ListBox?

How to clear the Listbox if its already bound with datasource? When you want to clear the Listbox, if the ListBox already bound with Datasource, you have to set the Datasource of Listbox as null.

listBox1.DataSource = null;

How to SelectedIndexChanged event in ListBox?

This event is fired when the item selection is changed in a ListBox. You can use this event in a situation that you want to select an item from your Listbox and according to this selection, you can perform other programming needs.

First, you should drag two listboxes on your Form. The first Listbox you should set the List as Datasource, the List contents follow:

List<string> nList = new List<string>();
nList.Add("First Quarter");
nList.Add("Second Quarter");

When you load this form, you can see the Listbox is populated with List and displayed the first quarter and second quarter. When you click the “First Quarter” the next Listbox is populated with first-quarter months and when you click “Second Quarter” you can see the second Listbox is changed to second-quarter months. From the following program, you can understand how this happened.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Collections.Generic;
namespace WindowsFormsApplication1
{
  public partial class Form1 : Form
  {
    public Form1()
    {
        InitializeComponent();
    }
    List  < string > fQ = new List  < string > ();
    List  < string > sQ = new List  < string > ();
    private void Form1_Load(object sender, EventArgs e)
    {
      fQ.Add("January");
      fQ.Add("February");
      fQ.Add("March");
      sQ.Add("April");
      sQ.Add("May");
      sQ.Add("June");
      List < string > nList = new List  < string > ();
      nList.Add("First Quarter");
      nList.Add("Second Quarter");
      listBox1.DataSource = nList;
    }
    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
      if (listBox1.SelectedIndex == 0)
      {
          listBox2.DataSource = null;
          listBox2.DataSource = fQ;
      }
      else if (listBox1.SelectedIndex == 1)
      {
          listBox2.DataSource = null;
          listBox2.DataSource = sQ;
      }
    }
  }
}

C# Listbox Column

A multicolumn ListBox places items into as many columns as are needed to make vertical scrolling unnecessary. The user can use the keyboard to navigate to columns that are not currently visible. First of all, you have Got or sets a value indicating whether the ListBox supports multiple columns.

public bool MultiColumn { get; set; }

The following C# code example demonstrates a simple multiple column ListBox.

private void button1_Click_1(object sender, EventArgs e)
{
  listBox1.HorizontalScrollbar = true;
  listBox1.MultiColumn = true;
  listBox1.ScrollAlwaysVisible = true;
  listBox1.Items.AddRange(new object[] {
  "January",
  "February",
  "March",
  "April",
  "May",
  "June",
  "July",
  "August",
  "September",
  "October",
  "November",
  "December"});
}

Listbox Item Double Click Event

Add an event handler for the Control.DoubleClick event for your ListBox.

The following program shows when you double click the Listbox Item that event handler open up a MessageBox displaying the selected item.

private void listBox1_DoubleClick(object sender, EventArgs e)
{
  if (listBox1.SelectedItem != null)
  {
    MessageBox.Show(listBox1.SelectedItem.ToString());
  }
}

Listbox vertical scrollbar

ListBox only shows a vertical scroll bar when there are more items then the displaying area. You can fix with ListBox.ScrollAlwaysVisible Property if you want the bar to be visible all the time. If ListBox.ScrollAlwaysVisible Property is true if the vertical scroll bar should always be displayed; otherwise, false. The default is false.

// Turn off the scrollbar.
ListBox1.ScrollAlwaysVisible = false;

Background and Foreground

The Listbox BackColor and ForeColor properties are used to set the background and foreground colors respectively. If you click on these properties in the Properties window, then the Color Dialog pops up and you can select the color you want.

Alternatively, you can set background and foreground colors from source code. The following code sets the BackColor and ForeColor properties:

listBox1.BackColor = System.Drawing.Color.Aqua;
listBox1.ForeColor = System.Drawing.Color.Black;

How to clear all data in a ListBox?

Listbox Items.Clear() method clear all the items from ListBox.

private void button1_Click_1(object sender, EventArgs e)
{
    listBox1.Items.Clear();
}

ListBox.ClearSelected Method Unselects all items in the ListBox.

// Clear all selections in the ListBox.
listBox1.ClearSelected();

Remove item from Listbox

public void RemoveAt (int index);

RemoveAt method removes the item at the specified index within the collection. When you remove an item from the list, the indexes change for subsequent items in the list. All information about the removed item is deleted.

Listbox Vs ListView Vs GridView

C# ListBox has many similarities with ListView or GridView (they share the parent class ItemsControl), but each control is oriented towards different situations. ListBox is best for general UI composition, mainly when the elements are always intended to be selectable. In contrast, ListView or GridView is best for data binding scenarios, mainly if virtualization or large data sets are involved. One most crucial difference is that listview uses the extended selection mode by default.


Comments are closed.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More