WPF error "the connectionString property has not been initialized"

NiceGirl13

New member
Joined
Nov 19, 2015
Messages
4
Programming Experience
Beginner
I have created a WPF project, where a user can insert the Servername in a textbox, and the connection should be saved in the app.config (in Runtime), ones that is done the data from a DB table should be loaded in the datagrid. When i press the connect button (after inserted the servername in the textbox) i get this message:

2nderror.PNG


The code is as followed:


App.config


C#:
    <configuration>
        <startup> 
            <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
        </startup>
      <connectionStrings>
        <add name="SQLconnectionString"
          connectionString=""
             providerName="System.Data.sqlclient"/>
      </connectionStrings>
    </configuration>
MainWindow.xaml.cs


C#:
    namespace CIA
    {
        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
            }    
   
            private void ButtonConnectServer_Click(object sender, RoutedEventArgs e)
            {
                try
                {
                    StringBuilder Con = new StringBuilder("Server=");
                    Con.Append(TextBoxServerName.Text);
                    Con.Append("; Database=SIT-DVH; Trusted_Connection=True;");
                    string strCon = Con.ToString();
                    updateConfigFile(strCon);
                    SqlConnection db = new SqlConnection();
                    ConfigurationManager.RefreshSection("connectionStrings");
                    db.ConnectionString = ConfigurationManager.ConnectionStrings["SQLconnectionString"].ToString();
                    // if connect to the server and database is there, load values into the datagrid
                    SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM Customer_Information",db);
                    DataTable data = new DataTable();
                    sda.Fill(data);
                    DataGridView_Customer_Information.DataContext = data;
                    //or change to this:
                    //DataGridView_Customer_Information.ItemsSource = data.DefaultView;
    
    
                }
    
                catch (Exception ex)
                {
                    MessageBox.Show("Error: \r\n" + ex);
                }
            }
    
            public void updateConfigFile(string con)
            {
                //Updating config file
                XmlDocument XmlDoc = new XmlDocument();
                //Loading the config file
                XmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
                foreach (XmlElement xElement in XmlDoc.DocumentElement)
                {
                    if (xElement.Name == "connectionStrings")
                    {
                        //setting the connectionStrings
                        xElement.FirstChild.Attributes[2].Value = SQLconnectionString;
                    }                    
                }
    
                //writing the connection string into the config file
                XmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
            }
        }
    }
 
Last edited:

JohnH

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
779
Location
Norway
Programming Experience
10+

JuggaloBrotha

Staff member
Joined
Apr 23, 2011
Messages
176
Location
Lansing, MI; USA
Programming Experience
10+
I have created a WPF project, where a user can insert the Servername in a textbox, and the connection should be saved in the app.config (in Runtime), ones that is done the data from a DB table should be loaded in the datagrid. When i press the connect button (after inserted the servername in the textbox) i get this message:

The code is as followed:

App.config
C#:
    <configuration>
        <startup> 
            <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
        </startup>
      <connectionStrings>
        <add name="SQLconnectionString"
          connectionString=""
             providerName="System.Data.sqlclient"/>
      </connectionStrings>
    </configuration>
MainWindow.xaml.cs


C#:
    namespace CIA
    {
        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
            }    
   
            private void ButtonConnectServer_Click(object sender, RoutedEventArgs e)
            {
                try
                {
                    StringBuilder Con = new StringBuilder("Server=");
                    Con.Append(TextBoxServerName.Text);
                    Con.Append("; Database=SIT-DVH; Trusted_Connection=True;");
                    string strCon = Con.ToString();
                    updateConfigFile(strCon);
                    SqlConnection db = new SqlConnection();
                    ConfigurationManager.RefreshSection("connectionStrings");
                    db.ConnectionString = ConfigurationManager.ConnectionStrings["SQLconnectionString"].ToString();
                    // if connect to the server and database is there, load values into the datagrid
                    SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM Customer_Information",db);
                    DataTable data = new DataTable();
                    sda.Fill(data);
                    DataGridView_Customer_Information.DataContext = data;
                    //or change to this:
                    //DataGridView_Customer_Information.ItemsSource = data.DefaultView;
    
    
                }
    
                catch (Exception ex)
                {
                    MessageBox.Show("Error: \r\n" + ex);
                }
            }
    
            public void updateConfigFile(string con)
            {
                //Updating config file
                XmlDocument XmlDoc = new XmlDocument();
                //Loading the config file
                XmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
                foreach (XmlElement xElement in XmlDoc.DocumentElement)
                {
                    if (xElement.Name == "connectionStrings")
                    {
                        //setting the connectionStrings
                        xElement.FirstChild.Attributes[2].Value = con;
                    }                    
                }
    
                //writing the connection string into the config file
                XmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
            }
        }
    }
If you're constructing the connection string why not use the variable you already have and pass it into the SqlConnection instead of saving it to the config file then retrieving it again. I also re-structured the code to make it more versatile:
        private DataTable _data = new DataTable();

        private void ButtonConnectServer_Click(object sender, EventArgs e) {
            SqlConnection db = null;
            SqlDataAdapter sda = null;
            try {
                var strCon = string.Format("Server={0}; Database=SIT-DVH; Trusted_Connection=True;", TextBoxServerName.Text.Trim());
                db = new SqlConnection(strCon);
                sda = new SqlDataAdapter("SELECT * FROM Customer_Information", db);

                db.Open();
                updateConfigFile(strCon);

                _data.Clear();
                sda.Fill(_data);
                
                DataGridView_Customer_Information.DataContext = _data;
                
                ConfigurationManager.RefreshSection("connectionStrings");
            }
            catch (Exception ex) {
                MessageBox.Show(string.Format("Error: \n{0}", ex));
            }
            finally {
                if (sda != null)
                    sda.Dispose();

                if (db != null) {
                    db.Close();
                    db.Dispose();
                }
            }
        }
 

NiceGirl13

New member
Joined
Nov 19, 2015
Messages
4
Programming Experience
Beginner
Hello Juggalobrotha, thanks for editing the code! well the reason that i want to store it in the app.config is becuase i want the connectionstring to be used in serveral windows, and only define the connectionstring ones. I was one method on doing it.
 

NiceGirl13

New member
Joined
Nov 19, 2015
Messages
4
Programming Experience
Beginner
I found the error, it was becuase i used an old name (before con now SQLconnectionString), xElement.FirstChild.Attributes[2].Value = SQLconnectionString; it was before xElement.FirstChild.Attributes[2].Value =con;
and it should add the string in:
xElement.FirstChild.Attributes[2].Value where i didnt had the connectionString in the same line. so it added it outside the connectionstring "". I just debugged it and checked the app.config in bin/debug and the values are correct set now.
 

JuggaloBrotha

Staff member
Joined
Apr 23, 2011
Messages
176
Location
Lansing, MI; USA
Programming Experience
10+
Hello Juggalobrotha, thanks for editing the code! well the reason that i want to store it in the app.config is becuase i want the connectionstring to be used in serveral windows, and only define the connectionstring ones. I was one method on doing it.
And my edits still retained that, though one of the changes I made as it stores it in the config file last (after not only setting the ConnectionString property via the constructor, but after the connection has been successfully opened. No sense in updating the config file with a bad connection string.
 
Top Bottom