When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles
ASPFAQs.com
Message Board
Related Web Technologies
User Tips!
Coding Tips

Sections:
Sample Chapters
Commonly Asked Message Board Questions
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Security
Stump the SQL Guru!
XML Info
Information:
Feedback
Author an Article
ASP ASP.NET ASP FAQs Message Board Feedback
Print this page.
Published: Sunday, January 27, 2002

From VB.NET to C# and Back Again, Part 3

By Darren Neimke and Scott Mitchell


  • Read Part 1
  • Read Part 2

  • In Part 2 we looked at more advanced differences between VB.NET and C#: namely the differences in operator usage; array usage, declaration, and allocation; and the functional differences. In this final part, we will (finally) look at a complete C# ASP.NET Web page and convert it to C#!

    - continued -

    Putting the Pieces Together - Converting an Actual ASP.NET Web Page
    Now that we've examined the major syntactical differences between VB.NET and C#, let's attempt to apply what we've learned and convert a C# ASP.NET Web page to VB.NET. The following code, written in C#, reads in the Products table from the GrocerToGo database into an OleDbDataReader, and then uses data binding to bind the data reader to a DataGrid. The code is as follows:

    <% @Import Namespace="System.Data" %>
    <% @Import Namespace="System.Data.OleDb" %>
    <script language="c#" runat="server">
      void Page_Load(Object sender, EventArgs e)
      {
        // 1. Create a connection
        const string strConnString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                                 "Data Source=C:\\Data\\GrocerToGo.mdb";
        
        OleDbConnection objConn = new OleDbConnection(strConnString);
        
        // You must open the db connection before populating the DataReader
        objConn.Open();	
    
        // 2. Create a command object for the query
        const string strSQL = "SELECT * FROM Products";
        OleDbCommand objCmd = new OleDbCommand(strSQL, objConn);
    
    
        // 3. Create/Populate the DataReader
        OleDbDataReader objDR = objCmd.ExecuteReader(CommandBehavior.CloseConnection);
    
        // Do data binding
        dgProducts.DataSource = objDR;
        dgProducts.DataBind();
      }
    </script>
    
    <html>
    <body>
      <h1>The <code>Products</code> Table</h1>
      <asp:datagrid runat="server" id="dgProducts" ForeColor="White" BackColor="Navy"
              Font-Name="Verdana" BorderWidth="0" CellPadding="4"
              HeaderStyle-Font-Bold="True"
              HeaderStyle-Font-Size="Small"
              Font-Size="Smaller"
              HeaderStyle-BackColor="Gray"
    	/>
    </body>
    </html>
    
    [View a live demo!]

    One thing to notice that wasn't mentioned before: in the constant strConnString note that to specify a backslash (\) in a C# string, we must use two consecutive backslashes (\\). This is because the backslash is the C# escape character - that is, we can insert a newline character using \n, or tab using \t. Therefore, to let C# know that we want a plain-Jane backslash and not some escaped character, we have to use two backslashes.

    Now, to convert this to VB.NET! First note that all of the code in the HTML section (between the <html> and the </html>) will need no changes - we just need to concern ourselves with the server-side script block (or code-behind page, if you're using that technique). First, let's change all of the function statements to VB.NET-proper function statements. That is:

    void Page_Load(Object sender, EventArgs e)
    {
       ...
    }

    becomes:

    Sub Page_Load(sender as Object, e as EventArgs)
       ...
    End Sub

    Note that we created a Sub since the C# function's return value was void. We also got rid of the curly braces, replacing the last one with End Sub. Finally, in the subroutine's arguments, we reordered the Type and arg names such that the arg name comes first followed by the Type. Next, we'll want to do some ticky-tack changes, such as renaming all of the constant delimiters in C#, //, to their VB.NET equivalents, ', removing all of the semicolons, and changing the C# string concatenation operator of + to the VB.NET operator, &. Next, let's change all variable (and constant) declarations from the C# format of Type VariableName to the VB.NET format of Dim VariableName as Type; for example, we'll make the following (among other) changes:

    const string strSQL = "SELECT * FROM Products"; -- becomes --
    Const strSQL as String = "SELECT * FROM Products"

    ... and ...

    OleDbCommand objCmd = new OleDbCommand(strSQL, objConn); -- becomes --
    Dim objCmd as OleDbCommand = New OleDbCommand(strSQL, objConn)

    Once we complete this we are, miraculously, done! The use of methods and objects from the .NET Framework (such as the OleDbCommand class, are identical regardless of the language being used. Note that translating from VB.NET to C# requires a bit more attention when it comes to the casing of classes and methods, since C# is case-sensitive. The final VB.NET translation can be seen below:

    <% @Import Namespace="System.Data" %>
    <% @Import Namespace="System.Data.OleDb" %>
    <script language="VB" runat="server">
      Sub Page_Load(sender as Object, e as EventArgs)
        '1. Create a connection
        Const strConnString as String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
                                 "Data Source=C:\Data\GrocerToGo.mdb"
        Dim objConn as New OleDbConnection(strConnString)
        objConn.Open()
    
        '2. Create a command object for the query
        Const strSQL as String = "SELECT * FROM Products"
        Dim objCmd as New OleDbCommand(strSQL, objConn)
    
        '3. Create/Populate the DataReader
        Dim objDR as OleDbDataReader
        objDR = objCmd.ExecuteReader()
    
        dgProducts.DataSource = objDR
        dgProducts.DataBind()
      End Sub
    </script>
    
    <html>
    <body>
      <h1>The <code>Products</code> Table - Looks Nice!</h1>
      <asp:datagrid runat="server" id="dgProducts" ForeColor="White" BackColor="Navy"
              Font-Name="Verdana" BorderWidth="0" CellPadding="4"
              HeaderStyle-Font-Bold="True"
              HeaderStyle-Font-Size="Small"
              Font-Size="Smaller"
              HeaderStyle-BackColor="Gray"
    	/>
    </body>
    </html>
    
    Pretty neat, eh? Essentially, translating from one language to another is not difficult, especially if you have a nice algorithm to aid in the translation. In fact, you could take this one step further and write a translator that morphed VB.NET code to C# code, and back again! I do strongly encourage you to practice such translations every now and then - it will make you more familiar with both VB.NET and C# and, in the end, make you a more knowledgeable developer!

    Happy Programming!

  • By Darren Neimke and Scott Mitchell


  • ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article