不允许更改连接字符串属性。连接当前状态是打开的

时间:2014-04-01 05:21:55

标签: c#

每个人都请帮助我。当我运行我的代码时。它给了我以下错误。

"Not allowed to change the connection string property.The connection current state is open."

这是我的代码。非常感谢任何帮助。我会等你的回复。谢谢你们所有人。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using RMSLibrary;

namespace RMS
{
public partial class InterfaceCityCountry : Window
{
    CreateAgentAccount creatAgentWin = new CreateAgentAccount();

    CitiesCountriesDAL citCountr = new CitiesCountriesDAL();
    string str =  ConfigurationManager.ConnectionStrings\
                     ["RMSDatabaseSqlProvider"].ConnectionString;

    public InterfaceCityCountry()
    {
        InitializeComponent();
        CenterWindowOnScreen();

        LoadListBoxCitiesCountries();
    }
    private void CenterWindowOnScreen()
    {
        double screenWidth = System.Windows.SystemParameters.PrimaryScreenWidth;
        double screenHeight = System.Windows.SystemParameters.PrimaryScreenHeight;
        double windowWidth = this.Width;
        double windowHeight = this.Height;
        this.Left = (screenWidth / 2) - (windowWidth / 2);
        this.Top = (screenHeight / 2) - (windowHeight / 2);
    }
    private void LoadListBoxCitiesCountries()
    {
        try
        {
            citCountr.OpenConnection(str);
            SqlDataAdapter sda = citCountr.GetCities();
            DataSet ds = new DataSet();

            sda.Fill(ds);

            lbCities.ItemsSource = null;
            lbCities.ItemsSource = ds.Tables[0].DefaultView;

            SqlDataAdapter sda2 = citCountr.GetCountries();
            DataSet ds2 = new DataSet();

            sda2.Fill(ds2);

            lbCountries.ItemsSource = null;
            lbCountries.ItemsSource = ds2.Tables[0].DefaultView;

            citCountr.CloseConnnection();
        }
        catch (Exception ex)
        {
            MyErrorMessage(ex);

        }
        finally
        {
            citCountr.CloseConnnection();
        }

    }
    private void btnDeleteCity_Click(object sender, RoutedEventArgs e)
    {


    }

    private void btnDeleteCountry_Click(object sender, RoutedEventArgs e)
    {

    }
    private void MyErrorMessage(Exception ex)
    {
        string messageBoxText = "Error Occured! Try Again.\n\n" + ex.Message;
        string caption = "Error";
        MessageBoxButton button = MessageBoxButton.OK;
        MessageBoxImage icon = MessageBoxImage.Error;
        MessageBox.Show(messageBoxText, caption, button, icon);
    }

    private void lbCities_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (lbCities.SelectedIndex > -1)
        {
            tbCity.Text = ((DataRowView)lbCities.SelectedItem)
             .Row.ItemArray[1].ToString();
            btnUpdateCity.IsEnabled = true;
        }
    }

    private void lbCountries_SelectionChanged
   (object sender, SelectionChangedEventArgs e)
    {
        if (lbCountries.SelectedIndex > -1)
        {
            tbCountry.Text =   ((DataRowView)lbCountries.SelectedItem)
                       .Row.ItemArray[1].ToString();
            btnUpdateCountry.IsEnabled = true;
        }
    }

    private void btnUpdateCity_Click(object sender, RoutedEventArgs e)
    {
        bool created = true;

        DataClassesDataContext dc = new DataClassesDataContext();
        try
        {
            string id = lbCities.SelectedValue.ToString();
            if ((from c in dc.Cities where c.Name 
               == tbCity.Text select c).Count() == 1)
            {
                MessageBox.Show("Name already Exist. Choose a different name");
                created = false;
            }
            else
            {
                var query = (from c in dc.Cities
                             where c.CityID == int.Parse(id)
                             select c).First();

                query.Name = tbCity.Text;
                dc.SubmitChanges();

            }

        }
        catch(Exception ex)
        {
            created = false;
            MyErrorMessage(ex);
        }

        if (created)
        {
            MessageBox.Show("Successfull");
            tbCity.Text = string.Empty;
            LoadListBoxCitiesCountries();
        }

    }

    private void btnUpdateCountry_Click(object sender, RoutedEventArgs e)
    {
        bool created = true;
        DataClassesDataContext dc = new DataClassesDataContext();

        try
        {
            string id = lbCountries.SelectedValue.ToString();

            if((from c in dc.Countries where 
              c.Name == tbCountry.Text select c).Count() == 1)
            {
                MessageBox.Show("Name already Exist. Choose a different name");
                created = false;
            }
            else
            {
                var query = (from c in dc.Countries
                             where c.CountryID == int.Parse(id)
                             select c).First();

                query.Name = tbCountry.Text;
                dc.SubmitChanges();
            }
        }
        catch (Exception ex)
        {
            created = false;
            MyErrorMessage(ex);
        }

        if (created)
        {
            MessageBox.Show("Successfull");
            tbCountry.Text = string.Empty;
            LoadListBoxCitiesCountries();
        }

    }

    private void City_CanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        bool hasError = Validation.GetHasError(tbCity);

        e.CanExecute = !hasError;
    }

    private void City_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        try
        {
            citCountr.OpenConnection(str);

            if (!(citCountr.CheckAlreadyExistCity(tbCity.Text.Trim())))
            {
                citCountr.InsertCity(tbCity.Text.ToString().Trim());

                LoadListBoxCitiesCountries();

                citCountr.CloseConnnection();

                MessageBox.Show("Added Successfully!");

                creatAgentWin.LoadCitiesAndCountries();

                tbCity.Text = "";
                tbCountry.Text = "";
            }
            else
            {
                citCountr.CloseConnnection();
                string msgtext = "City with same name
           already exist. You can't add same city twice. Try with Different name!";
                string caption = "Error";
                MessageBoxButton button = MessageBoxButton.OK;
                MessageBoxImage image = MessageBoxImage.Error;
                MessageBox.Show(msgtext, caption, button, image).ToString();
            }

        }
        catch (Exception ex)
        {
            string messageBoxText = "Error occured! Transection Failed. Try again";
            string caption = "Error";
            MessageBoxButton button = MessageBoxButton.OK;
            MessageBoxImage icon = MessageBoxImage.Error;
            MessageBox.Show(messageBoxText, caption, button, icon);


        }
        finally
        {
            citCountr.CloseConnnection();
        }
    }

    private void Country_CanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        bool hasError = Validation.GetHasError(tbCountry);

        e.CanExecute = !hasError;
    }

    private void Country_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        try
        {
            citCountr.OpenConnection(str);
            if (!(citCountr.CheckAlreadyExistCountry(tbCountry.Text.Trim())))
            {
                citCountr.InsertCountry(tbCountry.Text.ToString().Trim());

                LoadListBoxCitiesCountries();
                citCountr.CloseConnnection();

                MessageBox.Show("Added Successfully!");

                creatAgentWin.LoadCitiesAndCountries();
                tbCity.Text = "";
                tbCountry.Text = "";
            }
            else
            {
                citCountr.CloseConnnection();

                string msgtext = "Country with
            with same name already exist. You can't add
          same country twice. Try with Different name!";
                string caption = "Error";
                MessageBoxButton button = MessageBoxButton.OK;
                MessageBoxImage image = MessageBoxImage.Error;
                MessageBox.Show(msgtext, caption, button, image).ToString();
            }


        }
        catch (Exception ex)
        {
            this.MyErrorMessage(ex);

        }
        finally
        {
            citCountr.CloseConnnection();
        }

       }
    }
  }

1 个答案:

答案 0 :(得分:1)

我已经修复了我的问题因为连接已经打开了。我已经用if else语句检查了我的连接,以找到连接打开的位置。 用于检查连接是否打开或关闭连接。使用以下代码

   if (cn.State == ConnectionState.Open)
   {
     MessageBox.Show("open");
   }
   else {
        MessageBox.Show("closed");
        }

............................................... ............................................ 因此我把以下代码行

   citCountr.CloseConnnection();


   Before
   citCountr.CloseConnnection();

我的问题消失了.................. 谢谢.........和快乐..................