1

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();
}
  • 1
    what is `null`? have you debugged it? what is line 36? – Daniel A. White Jan 27 '12 at 14:21
  • My guess would be that there is no connection string named Database1.mdf and that is the line that it is breaking on. – Steve Jan 27 '12 at 14:22
  • possible duplicate of [What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net) – John Saunders Jan 27 '12 at 14:22
  • What does the connection string look like in your web.config file? Can you show it here (alter the credentials please). – DOK Jan 27 '12 at 14:23
  • actually there is long code the line number 36 is connection sting which i already written. –  Jan 27 '12 at 14:24

1 Answers1

3

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);
marc_s
  • 675,133
  • 158
  • 1,253
  • 1,388
  • 1
    thanks a lot i cant express my feelings but from last two days i am trying to find solution i am almost going mad thanks........ –  Jan 27 '12 at 14:41