Listbox Control in C#

In this article, we will learn how to use listbox in windows form in C#.

Let's create windows form.

Step 1
In Visual Studio select "File" = > "New" = > "Project..." then select C# Windows Forms Application then click Ok.

create windows form

Step 2
Let's create a listbox then you go "View" = > select "ToolBox" (Crtl+Alt+X) = > then select "All Windows Forms" = > Choose "listbox".

listbox
  1. Store procedure :
    create proc sp_getting_tblitems
    as
    begin
    select * from dbo.tblitems
    end 
    
    Application configuration file(App.config) :

    If you want to create "App.config" file then you press this shortcut key "Crtl+Shift+A" then you choose the Applicatiion configuration file(App.config)

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
    <connectionStrings>
    <add name="DBCS" connectionString="data source=.;database=dbSample;integrated security=SSPI" providerName="System.Data.SqlClient"/>
    </connectionStrings>
    </configuration>
    

    Note :-

    • data source: you enter your own sql server name(if you use local server then you use(.))
    • database : you enter your own database name
    • integrated security=SSPI means this is use windows authentication. If you use sql server authentication then you use the (Username=_yourusername;Password=_youpassword) then you replace in intergrated security portion.
    • Add the System.Configuration reference. if you don't know how to adding references right click your project folder references => add reference => select .Net => select System.Configuration => click OK
    Form1.cs file:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Data.SqlClient;
    using System.Configuration;
    namespace WindowsFormsApplication3
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
            private void Form1_Load(object sender, EventArgs e)
            {
                List<string> li = new List<string>();
                li = Getting();
                if (li.Count > 0)
                {
                    foreach (string c in li)
                    {
                        listBox1.Items.Add(c);
                    }
                }
                else
                    MessageBox.Show("You don't have enough data");
            }
            public List<string> Getting()
            {
                List<string> li = new List<string>();
                string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
                SqlConnection con = new SqlConnection(cs);
                SqlCommand cmd = new SqlCommand("sp_getting_tblitems", con);
                cmd.CommandType = CommandType.StoredProcedure;
                try
                {
                    con.Open();
                    SqlDataReader sdr = cmd.ExecuteReader();
                    while (sdr.Read())
                    {
                        li.Add(sdr["item"].ToString());
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    con.Close();
                }
                return li;
            }
        }
    }
    

    Note :

    • cmd.ExecuteReader() : Read the database whole table
    • CommandType.StoredProcedure : The command text are interpreted in store procedured.
    • con.Close() : You always close the database connection in finally block.
    Output :
    output listbox

    First of all, we'll know about the "listbox".

    ListBox displays a list which the user can select the items. We'll discuss about properties and function and events of listbox write down.

    "BackColor" changes the background color of listbox control.

    listBox1.BackColor = Color.AliceBlue;
    

    "BorderStyle" changes the style of listbox control border.

    listBox1.BorderStyle = BorderStyle.Fixed3D;
    

    "Click" when user mouse click on listbox control.

    listBox1.Click+=new EventHandler(listBox1_Click);
    private void listBox1_Click(object sender, EventArgs e)
    {
        MessageBox.Show("You clicked the listbox");
    }
    

    "Cursor" when user mouse hover on listbox control then cursor style changed.

    listBox1.Cursor = Cursors.Hand;
    

    "Dispose()" released all resources used by the System.ComponentModel.Component.

    listBox1.Dispose();
    

    "DoubleClick" when user mouse double click on listbox control.

    listBox1.DoubleClick+=new EventHandler(listBox1_DoubleClick);
    private void listBox1_DoubleClick(object sender, EventArgs e)
    {
        MessageBox.Show("You double click on listbox");
    }
    

    "Enabled" changes the listbox control are enable or not.

    listBox1.Enabled = true;
    

    "Focus()" focusing the listbox control.

    listBox1.Focus();
    

    "Font" changes the style of the text of listbox control.

    listBox1.Font = new Font("Arial", 12.0F, FontStyle.Bold);
    

    "ForeColor" changes the font color of listbox control.

    listBox1.ForeColor = Color.AliceBlue;
    

    "Height" set the height of listbox control.

    listBox1.Height = 200;
    

    "Hide()" hides the listbox control.

    listBox1.Hide();
    

    "MouseClick" when user click the listbox by mouse.

    listBox1.MouseClick+=new MouseEventHandler(listBox1_MouseClick);
    private void listBox1_MouseClick(object sender, MouseEventArgs e)
    {
    }
    

    "MouseDoubleClick" when user double click the by mouse.

    listBox1.MouseDoubleClick+=new MouseEventHandler(listBox1_MouseDoubleClick);
    private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
    {
    }
    

    "MouseEnter" when mouse pointer enters the listbox control.

    listBox1.MouseEnter+=new EventHandler(listBox1_MouseEnter);
    private void listBox1_MouseEnter(object sender, EventArgs e)
    {
    }
    

    "MouseHover" when mouse pointer rests/hover on the listbox control.

    listBox1.MouseHover+=new EventHandler(listBox1_MouseHover);
    private void listBox1_MouseHover(object sender, EventArgs e)
    {
    }
    

    "MouseLeave" when mouse pointer leaves the listbox control.

    listBox1.MouseLeave+=new EventHandler(listBox1_MouseLeave);
    private void listBox1_MouseLeave(object sender, EventArgs e)
    {
    }
    

    "MouseMove" when mouse pointer moves the listbox control.

    listBox1.MouseMove += new MouseEventHandler(listBox1_MouseMove);
    private void listBox1_MouseMove(object sender, MouseEventArgs e)
    {
    }
    

    "SelectedIndexChanged" events occurs when the user click listbox items.

    listBox1.SelectedIndexChanged+=new EventHandler(listBox1_SelectedIndexChanged);
    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
    }
    

    "ResetText()" resets all properties of listbox to its default values.

    listBox1.ResetText();
    

    "Show()" displays the listbox control.

    listBox1.Show();
    

    "Text" gets or sets text on listbox control.

    listBox1.Text = "hello";
    

    "Visible" gets or sets the listbox control visible or not.

    listBox1.Visible = true;
    


Top comments

Avatar0

chandan 05-04-2021

nice post

Write a comment


Name Email Message