user1830833
user1830833

Reputation: 181

C# connection data source issue

I am a beginner that used to do VB.NET and now trying to learn C#. I've been trying to set up few forms where I can insert data into sql table, but every time I try to run the ASPX page it says

"There were errors building the project. Do you want to continue with the preview anyway?"

When I view the error list I get two:

  1. Warning 1: Generation of the designer file for Track.aspx failed: Error HRESULT E_FAIL has been returned from a call to a COM component.
  2. Error 2: Unrecognized escape sequence

The Error is pointing to the server part of the connection which is this:

Data Source=iskra-laptop\SQLEXPRESS; (the S is highlighted with red)

I am not sure on how to fix this, any help is appreciated. Here are both codes, the form and the C# files,

p.s.: I am aware of SqlParameter, and I will use that once I fix this issue :)


UPDATE: I fixed the connection where I was missing an extra \, but the first error is still there. Now, my variables are not being recognized, it says it does not exist in the current context, and Yes, I double checked the id names, they are correct.

Upvotes: 0

Views: 170

Answers (1)

user47589
user47589

Reputation:

SqlConnection myConnection = new SqlConnection("Data Source=iskra-laptop\SQLEXPRESS;Initial Catalog=master;Integrated Security=True;Pooling=False");

Add a @ in front of the string:

SqlConnection myConnection = new SqlConnection(@"Data Source=iskra-laptop\SQLEXPRESS;Initial Catalog=master;Integrated Security=True;Pooling=False");

\ forms an escape sequence in strings. For example \n is a newline. \S isn't a valid escape sequence, so the compiler is crying.

The @ tells the compiler to treat the string literally. In other words, ignore the standard escape sequences.

Reading material on what the @ is: http://blogs.msdn.com/b/csharpfaq/archive/2004/03/12/what-does-an-before-the-start-of-a-string-literal-mean.aspx

Another solution is the following:

SqlConnection myConnection = new SqlConnection("Data Source=iskra-laptop\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True;Pooling=False");

Now we're escaping the slash, so \\S is interpreted as \S, as you intended.

Upvotes: 3

Related Questions