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;
using System.Data.SqlClient;
namespace Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string connStr = @"Data Source=YOUSEF-PC\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True";
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = connStr;
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select distinct city from employees";
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (reader.Read())
{
lstDepartments.Items.Add(reader["city"].ToString());
}
conn.Close();
}
private void lstDepartments_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstDepartments.SelectedText!=null)
{
lstEmployees.Items.Clear();
SqlConnection conn = new SqlConnection();
conn.ConnectionString = connStr;
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "select (firstname +' '+lastname) as fullname from employees where dept=@dept";
cmd.Parameters.AddWithValue("@dept", lstDepartments.SelectedText);
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
lstEmployees.BeginUpdate();
while (reader.Read())
{
lstEmployees.Items.Add(reader[0].ToString());
}
lstEmployees.EndUpdate();
conn.Close();
}
}
}
}