我是C#开发的新手,在尝试创建一个简单的应用程序时,我遇到了一个问题。我试图基于第一个ComboBox的SelectedIndexChanged属性填充ComboBox。 Visual Studio在第二个cn.Open(在private void cboCities_SelectedIndexChanged中)声明连接已经打开。但是,从我的代码中我相信我已经关闭了它?我做错了什么?任何和所有帮助都非常感谢。谢谢!
public partial class Form1 : Form
{
private SqlCeConnection cn = new SqlCeConnection(@"Data Source = \Program Files\ParkSurvey\ParkSurvey.sdf; Persist Security Info = False; Password = *");
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cn.Open();
SqlCeCommand command = cn.CreateCommand();
command.CommandText = "SELECT Name FROM Cities ORDER BY Name ASC";
SqlCeDataAdapter da = new SqlCeDataAdapter(command);
DataSet ds = new DataSet();
da.Fill(ds);
cn.Close();
cboCities.ValueMember = "CityId";
cboCities.DisplayMember = "Name";
cboCities.DataSource = ds.Tables[0];
cboCities.SelectedIndex = -1;
}
private void cboCities_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboCities.SelectedIndex > -1)
{
cn.Open();
string Cities = cboCities.SelectedValue.ToString();
SqlCeCommand command = cn.CreateCommand();
command.CommandText = "SELECT Name FROM Parks WHERE CityId ='" + Cities + "'";
SqlCeDataAdapter da = new SqlCeDataAdapter(command);
DataSet ds = new DataSet();
da.Fill(ds);
if (cn.State == ConnectionState.Open)
cn.Close();
cboParks.ValueMember = "ParkId";
cboParks.DisplayMember = "Name";
cboParks.DataSource = ds.Tables[0];
cboParks.SelectedIndex = -1;
}
}
}
答案 0 :(得分:2)
您应该更改代码以在每个方法中声明一个新连接并将其包装在using语句中。然后它将自动关闭并处理。