how to add this C# code connection string in app.config file for windows forms application program ?
i see examples of adding access db but i need to add excel file data , so can't find previous question on excel file connection in app.config.
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\MISD_report.xlsx" + #";Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1;ImportMixedTypes=Text;TypeGuessRows=0""";
Try this in web config file-
<connectionStrings>
<add name="Excel07ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties='Excel 8.0'" />
<add name="ConnStrName" connectionString="Data Source=database;Initial Catalog=database-name;Persist Security Info=True;User ID=your username;Password=your password" />
</connectionStrings>
i solved this myself .
app.config settings :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MSIDConn"
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\MISD_report.xlsx;Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1;ImportMixedTypes=Text;TypeGuessRows=0'"
providerName="System.Data.OleDb" />
</connectionStrings>
</configuration>
added these 2 lines in Form1.cs
using System.Data.OleDb;
using System.Configuration;
in button click event :
private void button1_Click(object sender, EventArgs e)
{
string excelconn = ConfigurationManager.ConnectionStrings["MSIDConn"].ConnectionString;
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = excelconn;
OleDbCommand command9 = new OleDbCommand
(
"SELECT P1, P2, P3 " +
" FROM [PE_Actual$] ", conn
);
DataSet ds9 = new DataSet();
OleDbDataAdapter adaptor9 = new OleDbDataAdapter(command9);
adaptor9.Fill(ds9, "testtable");
dataGridView1.DataSource = ds9.Tables[0].DefaultView;
}
Usually they sit in a section on their own:
<connectionStrings>
<add name="myConnectionName" providerName="myProvider" connectionString="Data Source=D:\MISD_report.xlsx;Extended Properties=Excel 12.0 Xml;HDR=YES;IMEX=1;ImportMixedTypes=Text;TypeGuessRows=0" />
</connectionStrings>
I do not know what the providerName for OLE/ Excel is or what name to use so the provider finds the correct connection string.
Related
C# on VisualStudio 2017. Windows Forms Application.
Hi all. I've read on the web that is not possible to use an .udl file in which write a ConnectionString for a SqlConnection. Is that true at today? And, if yes, there is an alternative way to use an external file for a ConnectionString in SqlConnetion?
I have to run project in 5 PCs that have different connection strings, for example:
PC1) Data Source=PCNAME\SQLEXPRESS;Initial Catalog=DBNEW;User ID=sa;Password=123;
PC2) Data Source=SERVER\SQLEXPRESS;Initial Catalog=DB;User ID=sa;Password=999;
[...]
Currently I use a string inside the project
string connSQL = "Data Source=.\\SQLEXPRESS;Initial Catalog=DBNEW;Persist Security Info=True;User ID=sa;Password=123;";
that I have to change five times for the five PCs' different connection.
I've tried anyway to connect with an .udl file
string connSQL = "Data Source=.\\SQLEXPRESS;AttachDbFile=C:\\connstring.udl";
that contains this
[oledb]
; Everything after this line is an OLE DB initstring
Data Source=PCNAME\SQLEXPRESS;Initial Catalog=DBNEW;Persist Security Info=True;User ID=sa;Password=123;
but of course it doesn't works.
Any ideas for an alternative solution?
Finally I found a solution. Thanks also to MethodMan's comment I later realized that you can use an external file to compile the connectionString, that is MyProjectName.exe.config, which is saved in the same directory as the software exe, and which has the same functions and settings of the App.config.
So what I did is create a new FormConn where you manually enter data for the connectionString, overwrite them in MyProjectName.exe.config and link this file to Form1 for SQL database management. Below the code.
In the Form1.cs:
using System.Configuration;
public Form1()
{
//Check if a connectionString already exists
//To the first slot there is a system configuration so 1 = no custom connectionString
if (ConfigurationManager.ConnectionStrings.Count == 1)
{
FormConn frmConn = new FormConn();
frmConn.ShowDialog();
try
{
//Restart Form1 in the case connectionString has changed
Application.Restart();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//Associates the custom connectionString to the string I will use in the code for operations that are connected to the DB.
StringSQL = ConfigurationManager.ConnectionStrings[1].ConnectionString;
}
In the FormConn.cs:
using System.Configuration;
using System.Reflections;
string appPath = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string appName = Environment.GetCommandLineArgs()[0];
string configFile = System.IO.Path.Combine(appPath, appName + ".config");
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
configFileMap.ExeConfigFilename = configFile;
System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
var sezione = (ConnectionStringsSection)config.GetSection("connectionStrings");<br>sezione.ConnectionStrings["MyProjectName.Properties.Settings.MyDataSetConnectionString"].ConnectionString = "Data Source=" + txtDataSource.Text + ";Initial Catalog=" + txtInitialCatalog.Text + ";Persist Security Info=True;User ID=" + txtUserID.Text + ";Password=" + txtPassword.Text + ";";
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");
this.Close();
And that's what I have inside my MyProjectName.exe.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="MyProjectName.Properties.Settings.MyDataSetConnectionString"
connectionString="Data Source=MyPcName\SQLEXPRESS;Initial Catalog=DB-1;Persist Security Info=True;User ID=sa;Password=123psw321"
providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>
This worked for me!
I've got a connection string to my database in a my app.config file. I want to using the app.config file rather than copying and pasting the string in the section i want to use it is.
My app.config file looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="Code_Churn_Analyiser.Properties.Settings.SVN_ConnectionString"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename="|DataDirectory|\SVN .mdf";Integrated Security=True;Connect Timeout=30;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
and my .cs file is currently like this:
private void sendToDB_Click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection("user id=username;" +"password=password;server=serverurl;" + "Trusted_Connection=yes;" + "database=database; " + "connection timeout=30");
}
I know that this is wrong but want to use the config file instead.
Can anyone help me in how I would go about doing this.
var connectionString=ConfigurationManager.ConnectionStrings["Code_Churn_Analyiser.Properties.Settings.SVN_ConnectionString"].ConnectionString;
Note : try to keep the name of the connectionstring simpler for readability purposes.
Also,Your assembly also needs a reference to System.Configuration.dll
If you want to access the ConnectionStrings property of your application-configuration file, you have to ...
add a reference to the System.Configuration-dll.
add this to the top of the file:
using System.Configuration;
Then you can access it in this way:
string conStr = ConfigurationManager.ConnectionStrings["Code_Churn_Analyiser.Properties.Settings.SVN_ConnectionString"].ConnectionString;
using(var con = new SqlConnection(conStr))
{
// ...
}
I wrote some code for getting a connection between asp.net and SQL Server but I have
Generally, the purpose of this code is to add 2 sets of data into the database using 2 text boxes.
This error is in web.config file:
Error 1 Character ';', hexadecimal value 0x3b is illegal in an XML name.
My configuration:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="myconectionstring"
connectionString="data source=.\SQLEXPRESS;initial catalogue=test;Integrated Security=SSPI"; providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
</configuration>
In code behind :
The type or namespace name 'SqlConnection' could not be found (are you missing a using directive or an assembly reference?)
My code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication3
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string cs = System.Configuration.ConfigurationManager.ConnectionStrings["myconectionstring"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("INSERTINTO TEST (name,fathername) VALUES('" + TextBox1.Text + "','" + TextBox1.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
best regards :)
=========================================
EDIT: I had done according your suggestions and there is no more error but the data isn't added to the database, actually nothing happens when i click on submit. :(
my code:
web.config:
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="myconectionstring"
connectionString="data source=.\SQLEXPRESS;initial catalogue=test;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
</configuration>
code behind :
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
namespace WebApplication3
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string cs = System.Configuration.ConfigurationManager.ConnectionStrings["myconectionstring"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("INSERT INTO Table_1 (name,fathername) VALUES('" + txt1.Text + "','" + txt2.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
txt1.Text = "";
txt2.Text = "";
con.Close();
}
}
}
Error1: You have added semicolon at the end of the connection string asbelow:
connectionString="data source=.\SQLEXPRESS;initial catalogue=test;
Integrated Security=SSPI";
^^^^^
Solution1: You need to move the semicolon inside connectionstring
Try This:
connectionString="data source=.\SQLEXPRESS;initial catalogue=test;
Integrated Security=SSPI;"
Error 2: You did not import the System.Data.SqlClient namespace to use the SqlConnection class members
Solution2:
You need to import System.Data.SqlClient; Namespace asbelow
using System.Data.SqlClient;
Solution 3: initial catalogue spelling is wrong, instead you should use Initial Catalog in your Connection string asbelow:
connectionString="data source=.\SQLEXPRESS;initial catalog=test;
Integrated Security=SSPI";
EDIT: Try the following code to get the exceptiondetails
protected void Button1_Click(object sender, EventArgs e)
{
string cs = System.Configuration.ConfigurationManager.ConnectionStrings["myconectionstring"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
try
{
string cs = System.Configuration.ConfigurationManager.ConnectionStrings["myconectionstring"].ConnectionString;
SqlCommand cmd = new SqlCommand("INSERT INTO TEST (name,fathername) VALUES('" + TextBox1.Text + "','" + TextBox1.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
String ErrorMsg=ex.ToString();
}
finally
{
con.Close();
}
}
You have a couple of errors. The first is that you have placed the semi-colon (;) outside the connectionString attribute value in the configuration it should be:
<connectionStrings>
<add name="myconectionstring"
connectionString="data source=.\SQLEXPRESS;initial catalogue=test;Integrated Security=SSPI;"
providerName="System.Data.SqlClient" />
</connectionStrings>
In your code file you have not imported the required namespace try adding:
using System.Data.SqlClient
I think you should have this configuration
<connectionStrings>
<add name="myconectionstring"
connectionString="data source=.\SQLEXPRESS;initial catalog=test;Integrated Security=SSPI;"
providerName="System.Data.SqlClient" />
</connectionStrings>
or
<connectionStrings>
<add name="myconectionstring"
connectionString="server=.\SQLEXPRESS;database=test;Integrated Security=SSPI;"
providerName="System.Data.SqlClient" />
</connectionStrings>
Use Initial Catalog or database instead of your initial catalogue= (or use server= and database= which are clearer and more obvious names, in my opinion)
This website http://www.connectionstrings.com/ is a great and extensive resource about how to build valid connection strings.
And of course, as all the others have mentioned - you need to add a using System.Data.SqlClient to your code file!
Error says clearly! Remove semicolon(;) from your connection string in configuration tag.
As shown below
<connectionStrings>
<add name="myconectionstring"
connectionString="data source=.\SQLEXPRESS;initial catalogue=test;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
</connectionStrings>
Also you missed the namespace,
using System.Data.SqlClient
when i run this code this error comes..
object reference not set to an instance of an object.
AutoCompleteStringCollection namesCollection = new AutoCompleteStringCollection();
string ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection con = new SqlConnection(ConString))
{
SqlCommand cmd = new SqlCommand("SELECT NAME FROM CUSTOMER", con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
AutoCompleteStringCollection MyCollection = new AutoCompleteStringCollection();
while (reader.Read())
{
MyCollection.Add(reader.GetString(0));
}
txtcname.AutoCompleteCustomSource = MyCollection;
con.Close();
}
Make sure your connection string in web.config something like
<connectionStrings>
<add name="ConString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>
Problem : i'm sure that you didn't declare the connection string in your config file under <ConnectionStrings> section.
OR
you might have declared it with some defferent Key name but not ConString.
Solution: you should declare the proper Connection String with Name ConString in your config file under <ConnectionStrings> section.
Make sure that your config file either App.Config or web.config has ConnectionString similar to following:
<connectionStrings>
<add name="ConString" connectionString="Data Source=ServerName;Intial Catalog=DatabaseName;UID=userID;Password=password;Integrated Security=True;" />
</connectionStrings>
I have a list of activity code and full name which is placed in web.config file.
But now they are increased to a large number. So I want to remove that from config file and to create a db and access it with help of configuration application block.
Any ideas would be helpful.
You have to add a App.Config file.
Add the connectionstring to the configuration
<configuration>
<connectionStrings>
<add name="connectionstringname"
connectionString="server=localhost;user id=your_bd_userid;Password=your_db_password;database=your_db_name"
providerName="MySql.Data.MySqlClient" />
</connectionStrings>
</configuration>
Your form code goes here
public void LoadActivityData
{
string cnString = ConfigurationManager.ConnectionStrings["connectionstringname"].ConnectionString;
MySqlConnection myConn = new MySqlConnection(cnString);
DataSet dsActivity = new DataSet();
string selectStr = "SELECT * FROM YourActivityTable";
MySqlDataAdapter adapter = new MySqlDataAdapter(selectStr, myConn);
adapter.Fill(dsActivity, "Activities");
grdView1.DataSource = dsActivity;
}
Use System.Configuration namespace to get the configurationmanager class.