1

我是 C# 开发的新手,在尝试创建一个简单的应用程序时,我遇到了一个问题。我正在尝试根据第一个 ComboBox 的 SelectedIndexChanged 属性填充 ComboBox。Visual Studio 在第二个 cn.Open(在私有 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;

        }
    }

}
4

1 回答 1

2

您应该更改代码以在每个方法中声明一个新连接并将其包装在 using 语句中。然后它会自动关闭并处理。

于 2012-04-27T19:41:24.097 回答