本帖最后由 小天 于 2013-8-14 09:47 编辑
希望大家帮忙分析一下,愁死我了,为什么cb省里添加的是对象而不是从数据库中读出来的字段?
代码如下
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.SqlClient;
namespace test10
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void cb省_SelectedIndexChanged(object sender, EventArgs e)
{
Province item = (Province)cb省.SelectedItem;
int id = item.Id;
using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDBFilename=|DataDirectory|\mydb1.mdf;Integrated Security=True;User Instance=True"))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select * from T_City where FProvinceId=@id";
cmd.Parameters.Add(new SqlParameter("id", id));
using (SqlDataReader reader = cmd.ExecuteReader())
{
cb市.Items.Clear();
while (reader.Read())
{
string name = reader.GetString(reader.GetOrdinal("FCity"));
cb市.Items.Add(name);
}
}
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDBFilename=|DataDirectory|\mydb1.mdf;Integrated Security=True;User Instance=True"))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select * from T_Province";
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Province item = new Province();
item.Id = reader.GetInt32(reader.GetOrdinal("Id"));
item.Name = reader.GetString(reader.GetOrdinal("FProvince"));
cb省.Items.Add(item);
}
}
}
}
}
}
class Province
{
public string Name { set; get; }
public int Id { set; get; }
}
}
|
|