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);
Related
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
I am trying to populate a WPF DataGrid with a SQL Server table, but I am getting this exception when I try to start the App (and it enters Break Mode):
An unhandled exception of type 'System.TypeInitializationException'
occurred in PresentationFramework.dll
Additional information: The type initializer for
'System.Windows.Application' threw an exception.
MY CODE
App.config
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<connectionstrings>
<add connectionstring="Data Source=*.*.*.*; User Id=**;Password=*****; Initial Catalog=Visitas;" name="ConString"/>
</connectionstrings>
MainWindow
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Fill()
{
string ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
string CmdString = string.Empty;
using (SqlConnection con = new SqlConnection(ConString))
{
CmdString = "SELECT * FROM employees_ext";
SqlCommand cmd = new SqlCommand(CmdString, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("EMPLOYEES_EXT");
sda.Fill(dt);
dataGridE.ItemsSource = dt.DefaultView;
}
}
private void button_Click(object sender, RoutedEventArgs e)
{
Fill();
}
}
Pretty simple code, but already checked everything and read tons of google info, but I am still not able to solve it :\
Since the XML is case-sensitive your connectionstring spelling is incorrect. So you should note that attribute names are case-sensitive. The s in connectionString should be Uppercase:
<connectionStrings>
<add connectionString="Data Source=*.*.*.*; User Id=**;Password=*****; Initial Catalog=Visitas;" name="ConString"/>
</connectionStrings>
Im encountering a problem when setting sqlconnection.
this is my Web.Config file :
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<connectionStrings>
<add name="SimpleDB"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\FluksikartoN\Documents\SimpleDB.mdf;Integrated Security=True;Connect Timeout=30"
providerName=".NET Framework Data Provider for SQL Server"/>
</connectionStrings>
</configuration>
So basically i want to add row "Hello" to sql table named "book" which has only one string column caled "Name" on button click , but i get error : "[Win32Exception (0x80004005): The network path was not found]" and i dont see anything wrong in sqlconnection set up.
aspx.cs file :
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Web.Services;
namespace ProjectWWW
{
public partial class WebForm1 : System.Web.UI.Page
{
[System.Web.Services.WebMethod]
public static string InsertData(string ID){
string connectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=C:/Users/FluksikartoN/Documents/SimpleDB.mdf;Integrated Security=True;Connect Timeout=30";
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("Insert into Book (Name) values(#Name)", con))
{
con.Open();
cmd.Parameters.AddWithValue("#Name", ID);
cmd.ExecuteNonQuery();
con.Close();
return "True";
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
InsertData("hELLO");
}
You've changed your backslashes to forward slashes. Change them back and use # to not treat them as escape characters:
string connectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\FluksikartoN\Documents\SimpleDB.mdf;Integrated Security=True;Connect Timeout=30";
or just pull it from app.config since you put it there as well:
string connectionString = ConfigurationManager.ConnectionStrings["SimpleDB"];
Why not use Web.Config connection string
string connectionString = ConfigurationManager.ConnectionStrings["SimpleDB"].ToString();
there is no need of specifying connection string on page when you have specified it in Web.Config
You can simply use like this in your .cs file
SqlConnection con = new SqlConnection(System.Configuration.CofigurationManager.ConnectionString["SqlConn"].ConnectionString.ToString());
I hope this will work for you.
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 want to do some sql code run in my webservice in c#
The code is just
[WebMethod]
public void GetCustomers()
{
SqlConnection MyConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Database1.mdf"].ConnectionString);
}
I think I got something wrong in this statement
now my database name is: Database1.mdf
now its table name is: t1
I get an error like
System.NullReferenceException: Object reference not set to an instance
of an object. at WebService1.Service1.GetCustomers() in
C:\Users\PRIYANK\Documents\Visual Studio
2008\Projects\WebService1\WebService1\Service1.asmx.cs:line 36
I don't know what to write in place of [Database1.mdf] so please write what to write in that place.
Here I place some code which might be helpful
[WebMethod]
public void GetCustomers()
{
SqlConnection MyConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Database1"].ConnectionString);
MyConn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = MyConn;
cmd.CommandText = "delete from t1 where name='1'";
cmd.ExecuteNonQuery();
}
You aren't supposed to put your data file's name in the ConnectionString[] element place. You should be putting your ConnectionString's name. In other words, look in your config file to where your <connectionStrings> section is. You will see a name=... for a connection string. Use that in your:
ConfigurationManager.ConnectionStrings["YourConnectionStringName"].ConnectionString
Example
Here is a sample from a sample config:
<connectionStrings>
<add name="Sales"
providerName="System.Data.SqlClient"
connectionString= "server=myserver;database=Products;uid=<user name>;pwd=<secure password>" />
</connectionStrings>
If you wanted to create a SqlConnection to the Products database, you would so this:
SqlConnection ProdDb =
new SqlConnection(ConfigurationManager.ConnectionStrings["Sales"].ConnectionString);