using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsTest
{
public partial class Form1 : Form
{
private static string connstring = "data source=local;Initial Catalog=roommanege;user=sa;pwd=";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(connstring))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select * from promary";
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Name = reader["proName"].ToString();
comboBox1.Items.Add(Name);
}
}
}
comboBox1.SelectedIndex = 0;//默认项是“请选择”(在控件的属性里面添加“请选择”)
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
comboBox2.Items.Clear();//在显示新数据前先把comboBox原有的数据清空
String id = comboBox1.SelectedIndex.ToString();//这选择的应该是对应省份的ID,而不是省份本身
using (SqlConnection conn = new SqlConnection(connstring))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select * from city where proID= '"+ id +"'";
using (SqlDataReader datareader = cmd.ExecuteReader())
{
while (datareader.Read())
{
string cityName = datareader["cityName"].ToString();
comboBox2.Items.Add(cityName);
}
}
}
}
}
}
}
CREATE TABLE [dbo].[city] (
[id] [int] IDENTITY (1, 1) NOT NULL ,
[proID] [int] NOT NULL ,
[cityName] [varchar] (10) COLLATE Chinese_PRC_CI_AS NOT NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[promary] (
[id] [int] IDENTITY (1, 1) NOT NULL ,
[proID] [int] NOT NULL ,
[proName] [varchar] (10) COLLATE Chinese_PRC_CI_AS NOT NULL
) ON [PRIMARY]
运行结果见图:
new SqlParameter("proID", proID)
参数名前面少了个@,应该会报错吧?还是你写错了?
你关掉过数据库吗?你用的是什么数据库?sql2000之类的数据库不能同时有两个游标读取数据,ExecuteReader是游标读数据库
简单点直接用vs自带的绑定数据库就可以啦!不用写代码的。。使用过!
跑堂来的,打断点自己跟下吧
代码没有报错吗