In this tutorial, I will teach you how to load data in the ListBox using C#.net and Microsoft SQL Server Management Studio 2005. ListBox is an item control, wherein it enables you to display a list of items from which the user can select by clicking it. This method has the ability to load more data in the ListBox from the database according to the functionalities in a certain situation.
To start with:
- Create a database and name it “dbname”. Then, insert data depending on your desire.
- Open Microsoft Visual Studio 2008 and create new Windows Form Application.
- Do the Form as follows.
- Go to the Solution Explorer, click the “View Code” to display the code editor.
- Declare all the classes and variables that are needed.
Note: Put using System.Data.SqlClient; above the namespace to access sql server library.
//initialize all classes
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
- Create a method for retrieving data in the SQL database to the ListBox.
private void retrieveLstBox()
//create a query for retrieving data in the database.
query = "SELECT * FROM tblname";
//initialize new Sql commands
cmd = new SqlCommand();
//hold the data to be executed.
cmd.Connection = conn;
cmd.CommandText = query;
//initialize new Sql data adapter
da = new SqlDataAdapter();
//fetching query in the database.
da.SelectCommand = cmd;
//initialize new datatable
dt = new DataTable();
//refreshes the rows in specified range in the datasource.
listBox1.DataSource = dt;
listBox1.DisplayMember = "Fullname";
catch (Exception ex)
- Go back to the design view, double click the Form and do the following codes for setting up the connection between SQL server and C#.net.
private void Form1_Load(object sender, EventArgs e)
//set a connection between SQL server and Visual C#
conn.ConnectionString = "Data Source=.\\SQLEXPRESS;database=dbname;trusted_connection=true;";
- Go back to the design view, double click the Button and do the following codes calling the retrieve method that you have created.
private void button1_Click(object sender, EventArgs e)
//calling the retrieve method
For all students who need programmer for your thesis system or anyone who needs a sourcecode in any programming languages. You can contact me @ :
Email – [email protected]
Mobile No. – 09305235027 – tnt