Converting VB to C#

tehon3299

Centurion
Joined
Jan 6, 2003
Messages
155
Location
Liverpool, NY
I am using the code below (VB) to insert things into an SQL database. I want to use this code on a C# page. How can I do this?

Visual Basic:
           	Dim MyCommand As New SqlCommand
			Dim MyConnection As New SqlConnection
			Dim MySQLDataAdapter as New SqlDataAdapter
			Dim SessionCmd As String

			SessionCmd = "INSERT INTO tmPicIndex (UserID, PicName, PicDesc) VALUES ('" & user & "', '" & savename.Value & "', 0)"
			
			MyConnection = New SqlConnection("server=(local);database=PictureShare;Trusted_Connection=yes")
							
			MyCommand = New SqlCommand(SessionCmd, MyConnection)

			MyCommand.Connection.Open()
				
				Try
					MyCommand.ExecuteNonQuery()
				Catch Exp As SQLException
					If Exp.Number = 2627
			            
					Else
			            
					End If
				End Try
				
			MyCommand.Connection.Close()
 
try this...

C#:
MyConnection = new SqlConnection("server=127.0.0.1;database=PictureShare;Trusted_Connection=yes");
MySQLDataAdapter = new SqlDataAdapter();
SessionCmd String = "INSERT INTO tmPicIndex (UserID, PicName, PicDesc) VALUES ('" & user & "', '" & savename.Value & "', 0)";
MyCommand = new SqlCommand(SessionCmd, MyConnection);

MyCommand.Connection.Open();
    
try
{
	MyCommand.ExecuteNonQuery();
}
catch(SQLException Exp)
{
	if (Exp.Number == 2627)
	{

	}
	else
	{
            
	}
}
MyCommand.Connection.Close();
 
If you want to use VB code in a C# project without having to
convert it all, you could compile the VB code into a class library
project that you can reference from your C# project. Then
you can use all the methods and properties in it just like any class.
 
You don't even need to compile it; just create a new VB project in
your solution and insert the class.
 
I used that code and it tells me that MyConnection is not declared. I'm importing the same things for SQL in VB and C#. Do I need to import something else?
 
The declaration for these variables should be as follows:

C#:
SqlConnection MyConnection = new SqlConnection("server=127.0.0.1;database=PictureShare;Trusted_Connection=yes");
SqlDataAdapter MySQLDataAdapter = new SqlDataAdapter();
string SessionCmd = "INSERT INTO tmPicIndex (UserID, PicName, PicDesc) VALUES ('" + user + "', '" + savename.Value + "', 0)";
SqlCommand MyCommand = new SqlCommand(SessionCmd, MyConnection);
 
Back
Top