Instance failure on VB but not C#

  • Thread starter Thread starter aarepasky
  • Start date Start date
A

aarepasky

Using ASP 2.0 express VB code to connect to a SQL Server express DB I
get an Instance failure, but doing the same thing with C# it works.
The error is on the open.

Here is the code:

Imports System
Imports System.Data
Imports System.Configuration
imports System.Web
imports System.Web.Security
imports System.Web.UI
imports System.Web.UI.WebControls
imports System.Web.UI.WebControls.WebParts
imports System.Web.UI.HtmlControls
Imports System.Data.SqlClient
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Me.Load
Dim conn As SqlConnection
Dim cmd As SqlCommand
Dim SelCmd As String
Dim coname As String
Dim dr As SqlDataReader

SelCmd = "select * from companies"

conn = New SqlConnection("Data
Source=KEVSTER\\SQLEXPRESS;Initial Catalog=lab;Persist Security
Info=True;User ID=lab;Password=pwd1")
conn.Open()

cmd = New SqlCommand(SelCmd, conn)
cmd.CommandType = Data.CommandType.Text

dr = cmd.ExecuteReader

While dr.Read()
coname = dr("companyname").ToString()
Response.Write(coname)
End While

dr.Close()
dr.Dispose()
conn.Close()
conn.Dispose()

End Sub
End Class

Now the C# below works:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection("Data
Source=kevster\\sqlexpress;Initial Catalog=lab;Persist Security
Info=True;User ID=lab;Password=pwd1");
cn.Open();


SqlCommand cm = cn.CreateCommand();
cm.CommandType = CommandType.Text;
cm.CommandText = "SELECT * FROM companies";

SqlDataReader dr = cm.ExecuteReader();

while (dr.Read())
{
Response.Write(dr["companyname"].ToString() + "<br />");
}

dr.Close();
dr.Dispose();
cm.Dispose();
cn.Close();
cn.Dispose();
}
}


So why does it work in C# and not VB?

Thanks,
riprip
 
Hard to tell. Try a single slash in the connection string:

KEVSTER\SQLEXPRESS


\ in c# is an escape character, so to have an actual \ you need to escape it
with itself \\

it has no special meaning in vb.net, so you actually have two slashes when
you shoudl only have one..

Karl
 
Karl,

Thanks that was it. It was bothering me that it was not working both
was. It was a learning process for me and it was bothering me that the
VB would not work. So the more I learn about .NET the more confident I
am.

Thanks again.

riprip
 
Back
Top