把连接字符串放到配置文件中
配置文件不能改名
1、添加一个app.config的文件 //使用应用程序配置文件的好处是修改数据库时不用重新编译程序
<connectionStrings>
<add name="str" connectionString="Data Source=.\sqlexpress;Initial Catalog=DataManager;Integrated Security=True"/>
</connectionStrings>
2、在项目中添加引用 System.configuration
3、添加命名控件using System.configuration
4、string connStr = ConfigurationManager.ConnectionStrings["str"].ConnectionString;
设已有数据库DBPromary 中有province表和city表
建一个辅助类Province
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WindowsFormsApplication2
{
class Province
{
public Province()
{ }
public Province(int proId, string proName)
{
this.ProId = proId;
this.ProName = ProName;
}
public int ProId { get; set; }
public string ProName { get; set; }
public override string ToString()
{
return this.ProName;
}
}
}
正文
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;
using System.Configuration;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//读取连接字符串
string connStr = ConfigurationManager.ConnectionStrings["str"].ToString();
private void Form1_Load(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(connStr))
{
string sql="select * from promary";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
conn.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
//把数据行,转换成Province对象
Province p = new Province();
p.ProName = dr["ProName"].ToString();
p.ProId = Convert.ToInt32(dr["ProId"]);
cboProvince.Items.Add(p);
}
}
}
}
if (cboProvince.Items.Count > 0)
{
//设置第一项被选中
cboProvince.SelectedIndex = 0;
}
}
private void cboVince_SelectedIndexChanged(object sender, EventArgs e)
{
//清空下拉菜单
cboCity.Items.Clear();
if (cboProvince.SelectedItem != null)
{
Province p = cboProvince.SelectedItem as Province;
if (p != null)
{
string sql = "select * from city where proId=" + p.ProId;
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
conn.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
cboCity.Items.Add(dr["cityName"]);
}
}
}
}
}
}
}
}
}