use of vb.net and c# in the same asp.net website

Hi Experts,

Here's my situation:

1) Am developing a website in asp.net in VB.NET (NOT using visual studio and NOT code behind except for my problem C# mini app as will be revealed as you read on).
2) We have a client registration page written in VB.NET which submits the new client data (name, dob, address etc) into to an SQL Server table and returns that table's primary key as the client's unique identifying variable which will be used in the pages that follow to link that client to the additional data that they need to enter.

In other words I need to hold that primary key as variable for a couple more pages where we seek to gain more data from the client.
 
3) The 2nd page holds a ListBox which allows the new client to sort items into their chosen order. This sortable ListBox (which we must use by the way) has been written in C# and includes a code behind file.

This 2nd page also holds a couple more data collection fields which are simple text boxes and drop down menus etc.

I need to utilise the primary key already collected and stored as a variable during page 1 (VB.NET) in page 2 when inserting the ListBox selection etc into another table.

My dilema is that I don't know what is and is not possible in ASP.NET in terms of moving a variable collected on a VB.NET page and carrying it across to a C# page.

Would it be best to:

a) Try and get the C# page converted into VB.NET using an online conversion tool which would resolve my problem?

or

b) Perhaps the variable collected on page 1 (VB.NET) can be carried across and utilised on page 2 (C#)? But please bear in mind page 3 will be in VB.NET and also needs to make use of this variable (ie move it from a C# page to a VB.NET page).

or

c) Mix C# and VB.NET on page 2 but essentially call it a VB.NET page? But then I suppose the C# code behind page won't work so I would have to apply the C# code from the code behind file (for the sortable ListBox) into a routine on the main body of page 2. If this is possible?

As you can tell I need some good advice.

Can anyone help clarify my options and supply any code snippets to help me get the job done?

Thanks.
 
ajd07Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

samtran0331Commented:
>>I need to hold that primary key as variable
How are you holding it? In a session? Cookie? Cache?

>>a) Try and get the C# page converted into VB.NET
Those conversion tools don't do that great a job.  But if your goal is consistency, then maybe you try.

>>Perhaps the variable collected on page 1 (VB.NET) can be carried across and utilised on page 2 (C#)? But please bear in mind page 3 will be in VB.NET and also needs to make use of this variable (ie move it from a C# page to a VB.NET page).

Since you're not using code-behind/vs.net, both the vb.net pages and the c#page can exist together and should work.

>>Mix C# and VB.NET on page 2
As far as I know, you can't do this on the same page with framework 1.x
The framework 2.0 is supposed to allow this.

>>As you can tell I need some good advice
That variable if stored in cache or session or you could even pass it between every page using querystring...the var should still be useable on all your pages. How are you storing the var?

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
raterusCommented:
There is no reason why you can't mix the two, but if you are using visual studio, it isn't going to be very cooperative.  in .Net 1.1 each assembly (.dll) has to be created with the same language.  However, you can have multiple assemblies in your /bin folder, compiled from each a different language.  What I'm getting at is you CAN do this, just don't expect Visual Studio to be your friend during the process...
ajd07Author Commented:
At the moment I am storing the variable ("pin") as per the following lines of code:

..........................................................................................
objCmd.Parameters.Add("@game_num", game_num.Text)
objCmd.Parameters.Add("@pin_num",SqlDbType.VarChar, 8).Direction=ParameterDirection.Output
 
objConn.Open()
objCmd.ExecuteNonQuery()

 
Dim pin As String = objCmd.Parameters("@pin_num").Value
objConn.Close() 'to close up of course now we have the player number.
.........................................................................................

In terms of the best way to manage it over to the next two pages I am very much open to suggestions.

Thanks.
OWASP Proactive Controls

Learn the most important control and control categories that every architect and developer should include in their projects.

samtran0331Commented:
Dim pin As String = objCmd.Parameters("@pin_num").Value
objConn.Close() 'to close up of course now we have the player number.        
Cache("pin") = pin

Then on your c# page, try adding this to page_load:

Response.Write(Cache("pin").ToString)


You can also replace the word "Cache" with "Session" and the var will be maintained in a session.
ajd07Author Commented:
Thanks for your input.

I have tried to convert the code into VB.NET using an online program but inevitably I am getting some errors.

I have therefore increased the points in the hope that someone can help me knock the code into final shape.

The working C# code essentially allows two ListBoxes side by side to have their list items swapped between each other either individually or the full list in one go (or a comination of the two).

I carefully converted the code section by section so I'm hoping it won't need a great deal of updating. However if you look at it and you feel that the conversion has put it beyond repair please let me know.

Samtran0331, 250 of the points will be yours anyway but the remaining will be based on helping me get the VB.NET into shape.

Hope you can help...

The first error message relates to the first Sub as it's not happy with "cont String SP_NAME = "getLeagueTeamsAlpha2". The error message reads "Keyword is not valid as an identifier".

Here is the code which I have divided into sections to make it easier to coment on...

section1.......................................................................................................................

Imports System
Imports System.Collections
Imports System.ComponentModel
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.Drawing
Imports System.Web
Imports System.Web.SessionState
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls

Public Class MakeSelection
       Inherits System.Web.UI

Protected Button1 As System.Web.UI.WebControls.Button
Protected ListBox2 As System.Web.UI.WebControls.ListBox
Protected Button2 As System.Web.UI.WebControls.Button
Protected Button3 As System.Web.UI.WebControls.Button
Protected Button4 As System.Web.UI.WebControls.Button
Protected Button5 As System.Web.UI.WebControls.Button
Protected ListBox1 As System.Web.UI.WebControls.ListBox

section 2..........................................................................................................................................................

Private  Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
                  If Not Page.IsPostBack Then
                        'SP name
                        const String SP_NAME = "getLeagueTeamsAlpha2"
 
                        ' Put user code to initialize the page here
                        Dim ds As DataSet =  New DataSet()
                        ds.Tables.Add(New DataTable("TestTable"))
 
                        'create a connection
                        Dim connection As SqlConnection =  New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
 
                        'create a command to execute the proc
                        Dim command As SqlCommand =  New SqlCommand(SP_NAME,connection)
                        command.CommandType = CommandType.StoredProcedure
 
                        'create an adapter as we need to fill a dataset
                        Dim adapter As SqlDataAdapter =  New SqlDataAdapter(command)
 
                        'open the connection
                        connection.Open()
 
                        'fill the dataset
                        adapter.Fill(ds, "TestTable")
 
                        'set the datasource of the list box
                        ListBox1.DataSource = ds
 
                        'Set the table within the List box to use
                        ListBox1.DataMember = "TestTable"
 
                        'set the value of the list items
                        ListBox1.DataValueField = "LETE_START_POSITION"
 
                        'set the text for the list items
                        ListBox1.DataTextField = "LETE_DESCRIPTION"
 
                        'bind the data
                        ListBox1.DataBind()
 
                        'for consistency store the value of the rows, can use this before updating the database
                        ViewState("ItemCount") = ListBox1.Items.Count
 
                  End If
End Sub

section 3......................................................................................................................................................

                        
#Region "Web Form Designer generated code
            override protected void OnInit"(EventArgs e)
            
InitializeComponent()
                  MyBase.OnInit(e)
                  
Private  Sub InitializeComponent()    
                  Me.Button1.Click += New System.EventHandler(Me.Button1_Click)
                  Me.Button2.Click += New System.EventHandler(Me.Button2_Click)
                  Me.Button3.Click += New System.EventHandler(Me.Button3_Click)
                  Me.Button4.Click += New System.EventHandler(Me.Button4_Click)
                  Me.Button5.Click += New System.EventHandler(Me.Button5_Click)
                  Me.Load += New System.EventHandler(Me.Page_Load)
 
End Sub
#End Region

section4.............................................................................................................................

Private  Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
 
                  Dim passValues() As Integer =  New Integer(CType(ViewState("ItemCount")) {}, __0__)
 
 
                  Dim i As Integer =  0
 
 
                  Dim item As ListItem
                  For Each item In ListBox2.Items
                        passValues(i) = Integer.Parse(item.Value)
 
 
                        i = i + 1
                  Next
 
 
 
                  If ListBox2.Items.Count = CType(ViewState("ItemCount"),Integer) Then
 
                        DataLayer.doStuff(passValues)
                  End If
End Sub

Private  Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs)
                  'move left to right
                  'make sure somthing is selected
                  If ListBox1.SelectedIndex <> -1 Then
                        'add selected item from left to right
                        ListBox2.Items.Add(ListBox1.Items(ListBox1.SelectedIndex))
                        'remove moved item
                        ListBox1.Items.Remove(ListBox1.Items(ListBox1.SelectedIndex))
 
                        'reset the selected item
                        ListBox1.SelectedIndex = -1
                        ListBox2.SelectedIndex = -1
 
                  End If
End Sub

Private  Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs)
                  'move right to left
                  'make sure somthing is selected
                  If ListBox2.SelectedIndex <> -1 Then
                        'add selected item from left to right
                        ListBox1.Items.Add(ListBox2.Items(ListBox2.SelectedIndex))
                        'remove moved item
                        ListBox2.Items.Remove(ListBox1.Items(ListBox1.SelectedIndex))
                        'reset the selected item
                        ListBox1.SelectedIndex = -1
                        ListBox2.SelectedIndex = -1
                  End If
End Sub

Private  Sub Button4_Click(ByVal sender As Object, ByVal e As System.EventArgs)
                  'Move all the items for the left to right menu
                  Dim item As ListItem
                  For Each item In ListBox1.Items
                        ListBox2.Items.Add(item)
                  Next
 
                  'clear the items out of the left box
                  ListBox1.Items.Clear()
End Sub
 
            Private  Sub Button5_Click(ByVal sender As Object, ByVal e As System.EventArgs)
                  'Move all the items for the left to right menu
                  Dim item As ListItem
                  For Each item In ListBox2.Items
                        ListBox1.Items.Add(item)
                  Next
 
                  'clear the items out of the left box
                  ListBox2.Items.Clear()
End Sub

section 5........................................................................................................................................

      Public Class DataLayer
 
            Public Shared  Sub doStuff(ByVal insertValues() As Integer)
                  'constant for the name of the proc
                  const String SP_NAME = "insertPlayerTeam2"
 
                  'create the connection
                  Dim connection As SqlConnection =  New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
 
                  'create a command
                  Dim command As SqlCommand =  New SqlCommand(SP_NAME,connection)
 
                  'set the command type
                  command.CommandType = CommandType.StoredProcedure
 
                  'open the connection
                  connection.Open()
 
                  'get the params for the command using the static method on SqlCommandBuilder
                  SqlCommandBuilder.DeriveParameters(command)
 
                  'plonk the params into a param array
                  Dim parameters() As SqlParameter =  New SqlParameter(command.Parameters.Count) {}
 
                  'shove the parameters into the array
                  command.Parameters.CopyTo(parameters, 0)
 
 
 
 
                  'now set each of the parameters by looping through the collection and comparing the names
                  Dim param As SqlParameter
                  For Each param In parameters
                        Select Case param.ParameterName
                              Case "@position1_team_num"
                                    param.Value = insertValues(0)
                                    Exit For
                              Case "@position2_team_num"
                                    param.Value = insertValues(1)
                                    Exit For
                              Case "@position3_team_num"
                                    param.Value = insertValues(2)
                                    Exit For
                              Case "@position4_team_num"
                                    param.Value = insertValues(3)
                                    Exit For
                              Case "@position5_team_num"
                                    param.Value = insertValues(4)
                                    Exit For
                              Case "@position6_team_num"
                                    param.Value = insertValues(5)
                                    Exit For
                              Case "@position7_team_num"
                                    param.Value = insertValues(6)
                                    Exit For
                              Case "@position8_team_num"
                                    param.Value = insertValues(7)
                                    Exit For
                              Case "@position9_team_num"
                                    param.Value = insertValues(8)
                                    Exit For
                              Case "@position10_team_num"
                                    param.Value = insertValues(9)
                                    Exit For
                              Case "@position11_team_num"
                                    param.Value = insertValues(10)
                                    Exit For
                              Case "@position12_team_num"
                                    param.Value = insertValues(11)
                                    Exit For
                              Case "@position13_team_num"
                                    param.Value = insertValues(12)
                                    Exit For
                              Case "@position14_team_num"
                                    param.Value = insertValues(13)
                                    Exit For
                              Case "@position15_team_num"
                                    param.Value = insertValues(14)
                                    Exit For
                              Case "@position16_team_num"
                                    param.Value = insertValues(15)
                                    Exit For
                              Case "@position17_team_num"
                                    param.Value = insertValues(16)
                                    Exit For
                              Case "@position18_team_num"
                                    param.Value = insertValues(17)
                                    Exit For
                              Case "@position19_team_num"
                                    param.Value = insertValues(18)
                                    Exit For
                              Case "@position20_team_num"
                                    param.Value = insertValues(19)
                                    Exit For
                        End Select
                  Next
 
 
                  'should now be able to execute the proc
                  command.ExecuteNonQuery()
 
                  'close the connection
                  connection.Close()
 
 
            End Sub
      End Class
End Class

samtran0331Commented:
cont String SP_NAME = "getLeagueTeamsAlpha2"

should be:

Const SP_NAME As String = "getLeagueTeamsAlpha2"
ajd07Author Commented:
Thanks samtran0331 you're bang on.

That's section 1 and 2 working hopefully sorted.

Now it's the first line of section 3 below which is causing a "String constant expected" error message.

........................................................................................................

#Region Web Form Designer generated code override protected Sub OnInit (ByVal e As EventArgs)
            
InitializeComponent()
                  MyBase.OnInit(e)
                  
Private  Sub InitializeComponent()    
                  Me.Button1.Click += New System.EventHandler(Me.Button1_Click)
                  Me.Button2.Click += New System.EventHandler(Me.Button2_Click)
                  Me.Button3.Click += New System.EventHandler(Me.Button3_Click)
                  Me.Button4.Click += New System.EventHandler(Me.Button4_Click)
                  Me.Button5.Click += New System.EventHandler(Me.Button5_Click)
                  Me.Load += New System.EventHandler(Me.Page_Load)
 
End Sub
#End Region

..........................................................................................................................................

Any thoughts?
samtran0331Commented:
a lot of your converted code seems a little out of place as compared to what vs.net creates when you "add new webform"...due to the differences in c# and vb.net...

I would suggest that you start a new vb webform, drag and drop the buttons and listboxes from the toolbox onto the form so it looks just like your c# page... that way, vs.net can wire them up properly the "vb way"...
for example, all your button_click subs are missing the "handles"
Private  Sub Button4_Click(ByVal sender As Object, ByVal e As System.EventArgs)
is normally:
Private  Sub Button4_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button4.Click


...then copy/paste just the code inside the subs from your converted page into the "new" page.

does that make sense?
I"m suggesting you rebuild the page in vb.net and not just convert the c# page and then replacing *all* the code that got converted.
samtran0331Commented:
>>Now it's the first line of section 3 below
This is what I'm talking about...how the conversion converted the c# code to vb.net....but the way the actual code behind is structured is different between c# and vb.net...

your section 3, vs.net would create a vb page more like this:
#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub
    Protected WithEvents txtStartDate As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtEndDate As System.Web.UI.WebControls.TextBox
    Protected WithEvents btnShowReport As System.Web.UI.WebControls.Button
    Protected WithEvents btnExcel As System.Web.UI.WebControls.ImageButton
    Protected WithEvents imgbtnPDF As System.Web.UI.WebControls.ImageButton
    Protected WithEvents lblDebug As System.Web.UI.WebControls.Label
    Protected WithEvents lblError As System.Web.UI.WebControls.Label
    Protected WithEvents pnlUsers As System.Web.UI.WebControls.Panel
    'Protected WithEvents dgUsers As System.Web.UI.WebControls.DataGrid
    Protected WithEvents dropSort As System.Web.UI.WebControls.DropDownList
    Protected WithEvents dgAgent As System.Web.UI.WebControls.DataGrid
    Protected WithEvents rfvStartDate As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents rvfEndDate As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents btnUpdate As System.Web.UI.WebControls.Button
    Protected WithEvents lblMSG As System.Web.UI.WebControls.Label

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region
ajd07Author Commented:
That's interesting and it looks like the best way to do it. The problem I have is that I do not have a copy of Visual Studio.net and I need to try to get this ListBox working today.

Based on this do you think that I'd be better off aborting the conversion attempt and accept that this page is going to have to be in C#?



samtran0331Commented:
If you're using codebehind, I don't know how/if you can compile it even if the full conversion was successful.
I think you can compile from the command line, but I've never needed to do it.
samtran0331Commented:
there are prebuilt controls that do the listbox to listbox thing...
http://www.asp.net/ControlGallery/ControlDetail.aspx?Control=2265&tabindex=2
samtran0331Commented:
there is also an opensource (free) version of vs.net...but I've never used it...just found it the other day.
http://www.icsharpcode.net/OpenSource/SD/
samtran0331Commented:
plus if you're only doing asp.net, there is WebMatrix
http://www.asp.net/webmatrix/

...but I don't believe it does the codebehind model...all your code has to be on the aspx page itself between script tags.
http://www.asp.net/webmatrix/
ajd07Author Commented:
Thanks samtran0331.

In order to get the functionality up and running I've run the ListBox on it's own C# page (+ code behind as created by another) and passed the variable FROM the VB.NET page (this will now be the logon page) page as follows:
...................................................................................................................
  ' display error, close connection, and exit method
   lblError.Text = "PIN and Password do not match, please try again."
    Session("pin_number") = "pin_number"
   connection.Close()
      Return
    End If
      End Sub
......................................................................................................................

I've then collected and tested it on the C# page from within the code behind file as follows:

.......................................................................................................................

//for consistency store the value of the rows, can use this before updating the database
                        ViewState["ItemCount"] = ListBox1.Items.Count;
                        
                  }
                              {      
                              if(Session["pin_number"]==null)
{
  Response.Write("no pin");
}
else
{
 Response.Write("pin variable present");
}
}

............................................................................................................................................................

This works (thanks for guidance!)

My last problem is that this C# page was supposed to have 2 more text boxes and one more simple list box (which  I would of course have liked to create using VB.NET). So my final question is simply:

1)  Because this page uses C# code (a language I know little about) created using Visual Studio (a program I don't have) and featuring a reasonably complex code behind file do I have any options in terms of adding 3 simple form fields to this page or it's code behind file?

I'm assuming that there's no way to create C# methods on a main page if it's header tag points to a code behind file?

I know there is probably no other option but thought I'd ask in case I've mised an opportunity to make life simpler.

Thanks.
samtran0331Commented:
>>I've then collected and tested it on the C# page from within the code behind file as follows
So let me get this straight....you were able to add code to the codebehind, did not recompile, AND the code worked?? I've never tested it, but I didn't think that was possible.

Well, if it did work for you, then I don't see why you couldn't also add more controls and code to add the 3 simple form fields you need to.

>>I'm assuming that there's no way to create C# methods on a main page if it's header tag points to a code behind file?
Yes it can.  As long as the subs and functions don't have conflicting names, an aspx page will recognize in line code and its codebehind code. I've inherited some compiled apps and have had to do this.

So you can add code to the aspx page using <script runat="server" ></script> tags.

g'luck!
ajd07Author Commented:
Yes, I added the variable testing code to the code behind file and it worked. Although I had to link to the code behind file like this:

<%@ Page language="c#" Inherits="MakeSelection" Src="make_prediction.aspx.cs" AutoEventWireup="false" %>

I think this was necessary because I'm not using VS.NET which although I know is a very powerful program I can't help getting the feeling that it binds some developers in to a dependency. Having said that I am about to install VS.NET 2005 beta because I know it's a powerful tool to have up your sleeve. By the way do you think I'll be able to run and amend projects written in VS 2003 (SDK 1.1) using VS 2005 Beta?

Thanks for all your help, I've learnt a lot during this question.

Have a good weekend!

AJD
samtran0331Commented:
AJD,
>>I had to link to the code behind file like this
I guess I learnt something too.  I didn't know you could run a codebehind file without compiling it.
I guess it basically acts as an "include" file when done this way.  
But realize that if you were in vs.net and could compile, when you deploy your app, you don't need the codebehind files in the deployment,all you deploy are the aspx files and the dll in the \bin folder....so compilation protects all your "real" code.
Using your method requires deployment of the *.cs and the *.vb files.....

>>I can't help getting the feeling that it binds some developers in to a dependency.
I wouldn't really call it "dependency"...I would call it using the right tool for the job! =0)

>>By the way do you think I'll be able to run and amend projects written in VS 2003 (SDK 1.1) using VS 2005 Beta?
I don't know...haven't messed with vs.net 2k5 at all.... Final releases from MS are buggy enough, much less a beta version....just don't trust if for client work and no time to fool with it.

Take care,
Sam
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.