This tutorial will teach you how to bind a ListBox in C#.

First, open Visual Studio, create a C# windows application project and then add a ListBox to the main form of that application.

Create the table in Microsoft SQL Server as shown below.

SQL Code

USE [TutorialsPanel]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[ProgrammingLanguage] (
    [ID]           INT           NOT NULL,
    [LanguageName] NVARCHAR (50) NULL
);

Design View

Table-Programming-Language-Design

Data View

Table-Programming-Language-Data-full

Related

Bind an ADO.NET DataTable to a ListBox using VB.NET

Now create a void function that will bind the ListBox.

C#

void BindMyListBox()
{
    string connectionStr = "Data Source=TUTORIALSPANEL-DB\SQLEXPRESS; Initial Catalog=TutorialsPanel;Integrated Security=True;";

    SqlConnection  cn = new SqlConnection(connectionStr);
    SqlDataAdapter da = new SqlDataAdapter();
    SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
    DataTable dt = new DataTable();
    cmd.CommandText = "Select LanguageName from ProgrammingLanguage Order by LanguageName ASC";
    da.SelectCommand = cmd;
    da.SelectCommand.Connection = cn;
    da.Fill(dt);
    myListBox.DataSource = dt;
    myListBox.DisplayMember = "LanguageName";
    myListBox.ValueMember = "LanguageName";

}

Now call this function from the form Load Event.

private void form_Load(object sender, EventArgs e)
{
    try
   {
        BindMyListBox();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

list box data

Now let’s show the selected item in a message box window when the user clicks on the ListBox. Use the ListBox event SelectedIndexChanged as shown below.

ListBox-Message-Box

Last modified: March 8, 2019

Comments

Write a Reply or Comment

Your email address will not be published.