locked
Connection String in a WPF Application RRS feed

  • Question

  • Hi, 
    In a WPF application that connects to DB wher should the connection string be written , Do we have to add an APP.config or do we have to write it in the app.xaml file.

    With Regards 
    litu Here
    Wednesday, February 18, 2009 10:45 AM

Answers

  • Hi,

    You can add in conrtol event or class but it should be in wpf application window.

    If you create new application in visual studion or visual c# or whatever it creates window1.xaml. you need to add connection string basically in class or event in that window1.xaml not in app.config or app.xaml.

    here is example to add in control event which is button :

    private void add_Click(object sender, RoutedEventArgs e)  
            {  
               
                 OleDbConnection myConn = new OleDbConnection(  
                     "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\\App_Data\\Database2.mdb");  
                   
                 string strQuery = "INSERT INTO registrant(regtype, date1, regboolean, regdate)
                Values ("+comboBox1.Text+", "+hostappformdate+", "+checkBox1+", "+hostdateofreg+")";  
     
                 OleDbCommand myComm = new OleDbCommand(strQuery,myConn);  
     
                 try 
                 {  
                     myConn.Open();  
                     myComm.ExecuteNonQuery();  
                     myConn.Close();  
                 }  
     
                 catch (OleDbException a)  
                 {  
                     Console.WriteLine("Error: {0}", a.Errors[0].Message);  
                 }  
     
                 MessageBoxResult saveBox = MessageBox.Show(  
                     "Data has been saved",  
                     "OK",  
                     MessageBoxButton.OK);  
                 
     
                  
            } 

    Here is example by creating a class (its sql connector instead of OleDb which i showed in 1st one):


    public class ConnectionHelper

        {

            public static SqlConnection GetConnection()

            {

                string connectionStr = "Data Source=MICROSOFT-JIGUO;Initial Catalog=CompanyTestDB;Integrated Security=True";

                SqlConnection conn = new SqlConnection(connectionStr);

                return conn;

            }

        }


    and you can use this class in your methods:



    SqlConnection conn = ConnectionHelper.GetConnection();


    Hope this helps.

    tj49


    ****Update: i am not sure if you can use in app.config or app.xaml file but this is what i am using from some times and it works for me. if someone else give so more information about that i would be of great intrest for me aswell

    thanks

    • Proposed as answer by tj49 Wednesday, February 18, 2009 11:33 AM
    • Marked as answer by Jim Zhou - MSFT Thursday, February 19, 2009 1:25 AM
    Wednesday, February 18, 2009 11:32 AM
  • Hi,

     

    You can save the connection string in Properties collection of current application in the constructor.

       public partial class App : Application

        {

            public App()

            {

                string connectionStr = "Data Source=MICROSOFT-JIGUO;Initial Catalog=CompanyTestDB;Integrated Security=True";

                Application.Current.Properties["connectionStr"] = connectionStr;

            }

    }

     

    Then you can use it in the application-scope like this:

    string str = Application.Current.Properties["connectionStr"].ToString();

     

    Hope this helps.

     

    Thanks.


    Jim Zhou -MSFT
    Thursday, February 19, 2009 5:07 AM

All replies

  • Hi,

    You can add in conrtol event or class but it should be in wpf application window.

    If you create new application in visual studion or visual c# or whatever it creates window1.xaml. you need to add connection string basically in class or event in that window1.xaml not in app.config or app.xaml.

    here is example to add in control event which is button :

    private void add_Click(object sender, RoutedEventArgs e)  
            {  
               
                 OleDbConnection myConn = new OleDbConnection(  
                     "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\\App_Data\\Database2.mdb");  
                   
                 string strQuery = "INSERT INTO registrant(regtype, date1, regboolean, regdate)
                Values ("+comboBox1.Text+", "+hostappformdate+", "+checkBox1+", "+hostdateofreg+")";  
     
                 OleDbCommand myComm = new OleDbCommand(strQuery,myConn);  
     
                 try 
                 {  
                     myConn.Open();  
                     myComm.ExecuteNonQuery();  
                     myConn.Close();  
                 }  
     
                 catch (OleDbException a)  
                 {  
                     Console.WriteLine("Error: {0}", a.Errors[0].Message);  
                 }  
     
                 MessageBoxResult saveBox = MessageBox.Show(  
                     "Data has been saved",  
                     "OK",  
                     MessageBoxButton.OK);  
                 
     
                  
            } 

    Here is example by creating a class (its sql connector instead of OleDb which i showed in 1st one):


    public class ConnectionHelper

        {

            public static SqlConnection GetConnection()

            {

                string connectionStr = "Data Source=MICROSOFT-JIGUO;Initial Catalog=CompanyTestDB;Integrated Security=True";

                SqlConnection conn = new SqlConnection(connectionStr);

                return conn;

            }

        }


    and you can use this class in your methods:



    SqlConnection conn = ConnectionHelper.GetConnection();


    Hope this helps.

    tj49


    ****Update: i am not sure if you can use in app.config or app.xaml file but this is what i am using from some times and it works for me. if someone else give so more information about that i would be of great intrest for me aswell

    thanks

    • Proposed as answer by tj49 Wednesday, February 18, 2009 11:33 AM
    • Marked as answer by Jim Zhou - MSFT Thursday, February 19, 2009 1:25 AM
    Wednesday, February 18, 2009 11:32 AM
  • Hi,

     

    You can save the connection string in Properties collection of current application in the constructor.

       public partial class App : Application

        {

            public App()

            {

                string connectionStr = "Data Source=MICROSOFT-JIGUO;Initial Catalog=CompanyTestDB;Integrated Security=True";

                Application.Current.Properties["connectionStr"] = connectionStr;

            }

    }

     

    Then you can use it in the application-scope like this:

    string str = Application.Current.Properties["connectionStr"].ToString();

     

    Hope this helps.

     

    Thanks.


    Jim Zhou -MSFT
    Thursday, February 19, 2009 5:07 AM
  • Hi Jim,

    it is very helpful thanks

    Friday, February 20, 2009 10:50 AM
  •  
    MessageBoxResult saveBox = MessageBox.Show(     
         "Data has been saved",     
         "OK",     
         MessageBoxButton.OK);    

    I don't know is your code makeshift, but I think this snippet should be in try block :-)
    urban.michal@o2.pl | Feel free to correct my english. I'll be thankful!
    Friday, February 20, 2009 11:53 AM
  • hi thanks for pointing it out. this is just a code snippet to show how to declare connection string in event handler method of control.

    you can do something like that after catch statement

    finally

                {

                    myConn.Close();

                    MessageBox.Show( "Data has been saved");
                }

    and delete myConn.Close(); from try statement:

    try 
                 {  
                     myConn.Open();  
                     myComm.ExecuteNonQuery();  
    }


    Hope this helps.
    Friday, February 20, 2009 2:09 PM
  • Hi tj49 :) Finally block runs always and "Data has been saved" message should be displayed only if no exceptions is thrown, so I think, that "Data has been saved" message should be in try block, because if exception is thrown data hasn't been saved, because of error to connect to OleDb :) Feel free to correct my english, if you find out some mistakes. ;)
    urban.michal@o2.pl | Feel free to correct my english. I'll be thankful!
    • Proposed as answer by sun55 Wednesday, November 7, 2012 4:01 PM
    Friday, February 20, 2009 7:31 PM
  • You can also store it in the app.config file, and call it through 

    System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"].ToString();

    Just beware that typically the app.config file is stored in plain text so the connection string is visible.

    • Proposed as answer by PalaSataJa Thursday, December 27, 2012 10:48 AM
    • Unproposed as answer by PalaSataJa Thursday, December 27, 2012 10:48 AM
    • Proposed as answer by PalaSataJa Thursday, December 27, 2012 10:49 AM
    Friday, February 20, 2009 8:20 PM
  • Thank you Jim Very Useful Help.

    -E.R.Sutharshan -Srilanka (Jaffna)-

    Tuesday, October 18, 2011 6:41 AM