Opt In (Do Not Edit Here)

Showing posts with label Multiple Data Sources. Show all posts
Showing posts with label Multiple Data Sources. Show all posts

Aug 3, 2011

ListBox with Data from Many Tables

Aim: To add ListBox items with values from different Tables or Views.

Problem:

During my Academic Project (The Event Management System) there is a situation where I need to display the Supplier’s Names from different Tables (such as Caterer, Manpower, and Advertisement etc.). Right now I have completed Academic year, but after lots of my efforts and guidance from many persons I succeed to achieve the intended target with simplest way.

Some weeks ago I placed same question on Mind Cracker Network. Here I tried to present the sample for the same portion of the code

The article contains the simplest way to achieve the mentioned aim.

Solution:

Requirements:

n One ListBox Control to display data.

n One Command Button to Perform associated actions

n Here I take Northwind Database as Sample Database

Justification:

  1. First we have to make some declaration as follows.

SqlConnection Conn =new SqlConnection("Data Source=.\\SqlExpress; "

+ "Initial Catalog=Northwind; Integrated security=True");

SqlDataReader rdr;

SqlCommand cmd;

//The target is very simple, we just have to

//execute simple SELECT statements with Data Reader using Command Object

  1. After Declaration, Now just execute the SELECT statement; add each item in Data Reader to the ListBox. For differencing data from each table you can add a TABLE name as ListBox item at beginning of the data being displayed.

private void button1_Click(object sender, EventArgs e)

{

Conn.Open();

//Supplier

listBox1.Items.Add("-----Suppliers----");

cmd = new SqlCommand("Select TOP(5) ContactName As PersonName from Suppliers", Conn);

rdr = cmd.ExecuteReader();

while (rdr.Read())

{

listBox1.Items.Add(rdr.GetValue(0).ToString());

}

rdr.Close();

//Customers

listBox1.Items.Add("-----Customers----");

cmd = new SqlCommand("Select TOP(5) ContactName As PersonName from Customers", Conn);

rdr = cmd.ExecuteReader();

while (rdr.Read())

{

listBox1.Items.Add(rdr.GetValue(0).ToString());

}

rdr.Close();

.

.

.

.

.

}

  1. Figure 1 shows the intended result

Figure 1

All Rights Reserved. 2014 Copyright SIMPLITONA

Powered By Blogger | Published By Gooyaabi Templates Designed By : BloggerMotion

Top