不允许更改连接字符串属性,连接当前状态是打开的 [英] Not allowed to change the connection string property the connection current state is open

查看:90
本文介绍了不允许更改连接字符串属性,连接当前状态是打开的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨..........每个人都请帮忙。当我运行我的代码。它给我以下错误。

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

这是我的代码。任何帮助都将不胜感激。我将等待回复。

先谢谢你们所有人。

................... .................................................. .............................

 使用系统; 
使用 System.Collections.Generic;
使用 System.Linq;
使用 System.Text;
使用 System.Threading.Tasks;
使用 System.Windows;
使用 System.Windows.Controls;
使用 System.Windows.Data;
使用 System.Windows.Documents;
使用 System.Windows.Input;
使用 System.Windows.Media;
使用 System.Windows.Media.Imaging;
使用 System.Windows.Shapes;

使用 System.Data.SqlClient;
使用 System.Configuration;
使用 System.Data;
使用 RMSLibrary;

命名空间 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();
}
私有 void CenterWindowOnScreen()
{
double screenWidth = System.Windows.SystemParameters.PrimaryScreenWidth;
double screenHeight = System.Windows.SystemParameters.PrimaryScreenHeight;
double windowWidth = .Width;
double windowHeight = this .Height;
this .Left =(screenWidth / 2 ) - (windowWidth / 2 );
this .Top =(screenHeight / 2 ) - (windowHeight / 2 );
}
private void LoadListBoxCitiesCountries()
{
尝试
{
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);

}
最后
{
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 = 错误发生!再试一次。\ n \\ n + ex.Message;
string caption = 错误;
MessageBoxButton button = MessageBoxButton.OK;
MessageBoxImage icon = MessageBoxImage.Error;
MessageBox.Show(messageBoxText,标题,按钮,图标);
}

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

私有 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 = ;

DataClassesDataContext dc = new DataClassesDataContext();
尝试
{
string id = lbCities.SelectedValue.ToString ();
if (( from c in dc.Cities 其中 c.Name == tbCity.Text 选择 c).Count()= = 1
{
MessageBox.Show( 名称已存在。请选择其他名称);
created = false ;
}
其他
{
var query = (来自 c dc.Cities
其中 c.CityID == int .Parse(id)
选择 c) 。第一();

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

}

}
catch (例外情况)
{
created = false ;
MyErrorMessage(ex);
}

如果(已创建)
{
MessageBox.Show( Successfull);
tbCity.Text = string .Empty;
LoadListBoxCitiesCountries();
}

}

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

尝试
{
string id = lbCountries .SelectedValue.ToString();

if (( from c in dc.Countries 其中 c.Name == tbCountry.Text 选择 c)。 Count()== 1
{
MessageBox.Show( < span class =code-string>名称已存在。请选择其他名称
);
created = false ;
}
其他
{
var query = (来自 c dc.Countries
其中 c.CountryID == int .Parse(id)
select c) 。第一();

query.Name = tbCountry.Text;
dc.SubmitChanges();
}
}
catch (例外情况)
{
created = ;
MyErrorMessage(ex);
}

如果(已创建)
{
MessageBox.Show( Successfull);
tbCountry.Text = string .Empty;
LoadListBoxCitiesCountries();
}

}

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

e.CanExecute =!hasError;
}

私有 void City_Executed( object sender,ExecutedRoutedEventArgs e)
{
try
{
citCountr。 OpenConnection的(STR);

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

LoadListBoxCitiesCountries();

citCountr.CloseConnnection();

MessageBox.Show( 成功添加!);

creatAgentWin.LoadCitiesAndCountries();

tbCity.Text = ;
tbCountry.Text = ;
}
else
{
citCountr.CloseConnnection();
string msgtext = 同名城市已经存在。你不能两次添加同一个城市。尝试使用其他名称!;
string caption = 错误;
MessageBoxButton button = MessageBoxButton.OK;
MessageBoxImage image = MessageBoxImage.Error;
MessageBox.Show(msgtext,caption,button,image).ToString();
}

}
catch (例外情况)
{
string messageBoxText = 发生错误!Transection失败。再试一次;
string caption = 错误;
MessageBoxButton button = MessageBoxButton.OK;
MessageBoxImage icon = MessageBoxImage.Error;
MessageBox.Show(messageBoxText,标题,按钮,图标);


}
最后
{
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()修剪());

LoadListBoxCitiesCountries();
citCountr.CloseConnnection();

MessageBox.Show( 成功添加!);

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

string msgtext = 已存在具有相同名称的国家/地区。您无法再添加相同的国家/地区。请尝试使用其他名称!;
string caption = 错误;
MessageBoxButton button = MessageBoxButton.OK;
MessageBoxImage image = MessageBoxImage.Error;
MessageBox.Show(msgtext,caption,button,image).ToString();
}


}
catch (例外情况)
{
this .MyErrorMessage(ex);

}
最后
{
citCountr.CloseConnnection();
}

}
}
}

解决方案

请检查以下链接。可以帮到你。



注意:分享你的连接是问题。下面的一个只是一个伪代码.Adjust根据你的情况。



 If(sqlconn.State == ConnectionState.Closed) //  如果关闭 
{
citCountr.OpenConnection(str);
}
其他 {
// 使用已打开的连接字符串而不再打开它。
}







不允许更改'ConnectionString'属性。连接的当前状态是开放的



不允许更改connecionstring属性。连接的当前状态是打开的 [ ^ ]



不允许更改'ConnectionString'属性。连接的当前状态是打开的


我已经修复了我的问题因为连接已经打开了。我已经用if else语句检查了我的连接,找到了哪里连接打开。

用于检查连接是否打开或关闭。使用以下代码



if(cn.State == ConnectionState.Open)

{

MessageBox。显示(打开);

}

else {

MessageBox.Show(" closed");

}

...................................... .................................................. ...........

因此我输入以下代码行



citCountr.CloseConnnection();





之前

citCountr.CloseConnnection();



我的问题消失了..................

谢谢.........并且很开心.. ................

Hi..........Every one please help.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 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();
            }
            
        }
    }
}

解决方案

Please check below links.May be helped to you.

Note: Sharing your connections is the problem.Below one is just a pseudo code.Adjust it according to your situation.

If( sqlconn.State == ConnectionState.Closed)//if closed
{
  citCountr.OpenConnection(str);
}
else{
   //use already opened connection string without opening it again.
}




Not allowed to change the 'ConnectionString' property. The connection's current state is open

"Not allowd to change the"connecionstring property".The connection's current state is open "[^]

Not allowed to change the 'ConnectionString' property. The connection's current state is open


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..................


这篇关于不允许更改连接字符串属性,连接当前状态是打开的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆