I am trying to create page in asp.net page and I am getting the following error
Error:-System.NullReferenceException: Object reference not set to an instance of an object. at TestdateAssistor.user_info.Button1_Click1(Object sender, EventArgs e)
at this line
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=LAPTOP-O9SI19I0\SQLEXPRESS;Integrated Security=True"].ConnectionString);
This is my complete code
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True"].ConnectionString);
conn.Open();
String insert = "insert into Table (NAME,ADDRESS,MOBILE NO,ADHAR NO,DOB) values (#name,#add,#mob,#adhar,#dob)";
SqlCommand com = new SqlCommand(insert,conn);
com.Parameters.AddWithValue("#name",TextBox1.Text);
com.Parameters.AddWithValue("#add",TextBox2.Text);
com.Parameters.AddWithValue("#mob",TextBox3.Text);
com.Parameters.AddWithValue("#adhar", TextBox4.Text);
com.Parameters.AddWithValue("#dob", TextBox5.Text);
com.ExecuteNonQuery();
Response.Write("Successful Registration!!");
conn.Close();
}
catch (Exception ex)
{
Response.Write("Error:-" + ex.ToString());
}
What changes should I make in the connection string?
You’re using the connection string as a key to your connection strings defined in the Web.config. So you need to define the connection string there and give it a name, then reference it in the code by name:
Web.config:
<connectionStrings>
<add name="myConnectionString" connectionString="Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True" />
</connectionStrings>
Code:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
The ConnectionStrings is a collection automatically built for you by the framework. Its content is retrieved from the web.config where you should have it defined in the proper section.
Then you retrieve its value passing the Name between the square brackets not the whole connectionstring.
string cnString = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
SqlConnection conn = new SqlConnection(cnString);
and in your web.config you add the proper definition for your connectionstring
<configuration>
<connectionStrings>
<add name="MyConnection" connectionString="Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True"/>
</connectionStrings>
.....
</configuration>
Error:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True"].ConnectionString);
Solution 1:
in main program (.cs)
SqlConnection conn = new SqlConnection("Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True");
Solution 2:
in web.config
<configuration>
<connectionStrings>
<add name="MyConnection" connectionString="Data Source=LAPTOP-O9SI19I0\\SQLEXPRESS;Integrated Security=True"/>
</connectionStrings>
</configuration>
in main program (.cs)
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;);
reference: https://msdn.microsoft.com/en-us/library/d7469at0(v=vs.110).aspx
Related
i trying to run query using C#, i am getting the following problem
An OLE DB Provider was not specified in the ConnectionString. An example would be, 'Provider=SQLOLEDB;
my code
string strConString = System.Configuration.ConfigurationManager.ConnectionStrings["WorkflowConnStr"].ConnectionString.ToString();
string sqlstr = "select * from table"
OleDbConnection myConnection = new OleDbConnection(strConString);
try
{myConnection.Open();}
catch (Exception err)
{ System.Diagnostics.Debug.WriteLine(err.Message); }
OleDbCommand myCommand = new OleDbCommand(sqlstr, myConnection);
OleDbDataReader reader = myCommand.ExecuteReader();
web.config
<add name="WorkflowConnStr" connectionString="Data Source=Server;Initial Catalog=DBName;user id=usr;password=password" providerName="System.Data.OleDb.OleDbConnection"/>
any suggestion ?
Try adding this to your connection string,
Provider=SQLNCLI10.1
So it would be;
<add name="WorkflowConnStr" connectionString="Data Source=Server;Initial Catalog=DBName;user id=usr;password=password;Provider=SQLNCLI10.1" providerName="System.Data.OleDb.OleDbConnection"/>
Use SqlConnection instead of OleDbConnection.
I try to connect to my database and I can do that using following code:
using (SqlConnection conn =
new SqlConnection("Data Source=.\\SQLEXPRESS; Initial Catalog=DocumentManager; Persist Security Info=True; Integrated Security=True"))
{ ... }
But, when I try this:
string connectionString = ConfigurationManager.ConnectionStrings["DatabaseConnection"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString)) { ... }
it doesn't work anymore. My Connection String looks like this:
<add name="DatabaseConnection" connectionString="Data Source=.\\SQLEXPRESS; Initial Catalog=DocumentManager; Persist Security Info=True; Integrated Security=True" />
And, I can read the connectionString variable and it looks exactly like the string in the first case.
Your in-code connection string has an escaped "\" in it.
Try changing your web.config to:
<add name="DatabaseConnection" connectionString="Data Source=.\SQLEXPRESS; Initial Catalog=DocumentManager; Persist Security Info=True; Integrated Security=True" />
The "\" does not need to be escaped in your web.config.
This is an example of escaping the backslash.
Try this
string connectionString = System.Configuration.ConfigurationManager.AppSettings("DatabaseConnection");
I have a grid which has a dasource selected sqlDataSource2. I have not built any query in the datasource. I have a dropdownlist with two items and I would like to select the query from the dropdownlist and after selection of the query update the grid to show the result.
This is what I have tried so far:
protected void Page_Load(object sender, EventArgs e)
{
Query1();
}
protected void Query1()
{
//if (this.IsPostBack)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["PMIcommConnectionString"].ConnectionString;
SqlDataSource2.SelectCommand = #"SELECT YEAR(custDecDate), SUM(valueXX), SUM(valueYY)
FROM bids
WHERE forBid ='"+ DropDownList3.SelectedValue +"'GROUP BY YEAR(custDecDate)'";
SqlDataSource2.DataBind();
RadGrid1.DataBind();
}
}
This is my connection string:
<add name="PMIcommConnectionString" connectionString="Data
Source=WIN-72PL3253COR\SQLEXPRESS;Initial Catalog=PMIcomm;Integrated
Security=True" providerName="System.Data.SqlClient" />
I get an error "Connection string has not been initialized" on the last line. How can I make this working? Beside the error I am getting, I am not sure if this is the correct way to do this. Sorry for asking such simple thing, I am a selflearning beginner.
The connection string is not in AppSettings.
What you're looking for is in:
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["PMIcommConnectionString"].ConnectionString;
Web.config:
<connectionStrings>
<add name="PMIcommConnectionString" connectionString="Data
Source=WIN-72PL3253COR\SQLEXPRESS;Initial Catalog=PMIcomm;Integrated
Security=True"/>
</connectionStrings>
Code Behind .cs:
using System.Configuration;
using System.Data.SqlClient;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["PMIcommConnectionString"].ConnectionString);
I need to connect C# with SQL Server database using app.config.
My code is:
public partial class Form1 : Form
{
string connectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
public Form1()
{
InitializeComponent();
}
public void InsertDeleteUpdate(string query)
{
try
{
SqlConnection Conn = new SqlConnection(connectionString);
Conn.Open();
SqlCommand comm = new SqlCommand(query, Conn);
comm.ExecuteNonQuery();
Conn.Close();
MessageBox.Show("Succeeded");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
and in app.config I have:
<connectionStrings>
<add name="Test1"
providerName="System.Data.SqlClient"
connectionString="Data Source=KSPR1WS126;Initial Catalog=Test1;User ID=sa" />
</connectionStrings>
but I get an error and I can't fix it:
ConfigurationErrorExeption was Unhandled Configuration system
failed to initialize
Can anyone help me please ?
Try:
var connectionString = ConfigurationManager.ConnectionStrings["Test1"].ConnectionString;
You're referencing Conn as the connection string name but referenced it as Test1 in the App.Config
Try this..
<connectionStrings>
<add name="Conn" providerName="System.Data.SqlClient"
connectionString="Data Source=KSPR1WS126;Initial Catalog=Test1;User ID=sa" />
</connectionStrings>
Try below code and then check
string connectionString = ConfigurationManager.ConnectionStrings["Test1"].ConnectionString;
I'm using this code to read the connection string from my app.config file but it always return a null value. My App.config file is under my project. Both methods are resulting null values:
public SqlConnection getConnection()
{
try
{
// connectionString = ConfigurationManager.AppSettings["dbConn"];
connectionString = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
connectionString = System.Configuration.ConfigurationManager.AppSettings["dbConn"];
sqlConnection = new SqlConnection(connectionString);
sqlConnection = new SqlConnection(connectionString);
}
catch (Exception ex)
{
}
return sqlConnection;
}
This is my app.config file declaration:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="dbConn" providerName="System.Data.SqlClient"
connectionString="Data Source=VANYA\SQLEXPRESS;Initial Catalog=mydatabase;User Id=sa;Password=123" />
</connectionStrings>
</configuration>
I think your problem that you try to read connection string twice, first you do it right, and second time you do it wrong, so just remove second line:
connectionString = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
sqlConnection = new SqlConnection(connectionString);
ConfigurationManager.AppSettings used to access <appSettings>...</appSettings> section of the config.
Can you please try
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="dbConn" providerName="System.Data.SqlClient"
connectionString="Data Source=VANYA\SQLEXPRESS;Initial Catalog=mydatabase;User Id=sa;Password=123" />
</connectionStrings>
<appSettings>
<add key="dbConn" value="Data Source=VANYA\SQLEXPRESS;Initial Catalog=mydatabase;User Id=sa;Password=123" />
</appSettings>
</configuration>
Then use the second method.
Make sure you select the App.Config file in the solution explorer and in the property window select Copy to Output Directory to Copy Always. Now Build the application and try again.
You simple define connection string in one class and call that string.....
public class Connection
{
/// <summary>
/// Connection String
/// </summary>
public static string ConnectionString
{
get
{
return ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
}
}
}
//Returning connction string
sqlConnection conn = new SqlConnection(Connection.ConnectionString);
connectionString=global::myProject.Properties.Settings.Default.myConnectionString