-
May 24th, 2016, 09:33 PM
#1
connection string config help
ive recently learnt that you can store connection strings in a .config file so i created one (connectionstring) for to test this out however whenever i run this i get a object reference not set to an instance of an object ive referenced system.configuration.dll and im using system.configuration; but i cant figure out why this is throwing this error
Code:
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
namespace ExperimentingApplication
{
/// <summary>
/// Interaction logic for AuthenticationScreen.xaml
/// </summary>
public partial class AuthenticationScreen : Window
{
public AuthenticationScreen()
{
InitializeComponent();
}
private void UserInputKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter) //only accepts enter key
{
string dbconnection = ConfigurationManager.ConnectionStrings["Database"].ConnectionString; //if there is anyway of condensing it please let me know
SqlConnection connection = new SqlConnection(dbconnection);
connection.Open();
if (connection.State == ConnectionState.Open) // if connection.Open was successful
{
MessageBox.Show("You have been successfully connected to the database!");
}
else
{
MessageBox.Show("Connection failed.");
}
this is the connectionstring.config file
Code:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="Database" connectionString="Server=******-*******;Database=TestDatabse;Trusted_Connection=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
-
May 24th, 2016, 09:34 PM
#2
Re: connection string config help
-
May 25th, 2016, 12:19 AM
#3
Re: connection string config help
You need to add a config file to your project and put the connectionstrings section in there. To do this, click add new item and choose config file.
This will add an app.config file to your project and when you compile the project, it will automatically generate an myprojectname.exe.config file in the output folder.
It isn't working for you because you have a connectionstring.config file which the program knows nothing about.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|