user3483659
user3483659

Reputation: 21

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

Every one please help me.When i run my code.It gives me the following error.

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

Here is my code.Any help will most be appreciated. I will be waiting for your reply.Thanks in advance to all of you.

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();
        }

       }
    }
  }

Upvotes: 1

Views: 4254

Answers (1)

user3483659
user3483659

Reputation: 21

I have fixed my problem Because the connection was already open.I have checked my connection with if else statement to find that where is the connection open. for checking the connection wither the connection is open or close. use the following code

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

........................................................................................... and hence i put the following line of code

   citCountr.CloseConnnection();


   Before
   citCountr.CloseConnnection();

and my problem gone away.................. Thanks.........and happy..................

Upvotes: 1

Related Questions