Joe Yan
Joe Yan

Reputation: 2095

How to convert Var from C# to VB?

I found the following C# code which is useful for me:

public partial class Default2 : System.Web.UI.Page 
  { 
    protected void Page_Load(object sender, EventArgs e) 
    { 
        if (Session["EID"] != null) 
        { 
            int EmpID = (int)Session["EID"]; 

            DataClassesDataContext dc = new DataClassesDataContext(); 
            var empInfo = from emp in dc.EmployeeLogins 
                          where emp.EmployeeID == EmpID 
                          select new
                          { 
                                     emp.EmployeeLoginKey, 
                                     emp.EmployeeID, 
                                     emp.username, 
                                     emp.passwd 
                          }; 

           foreach (var v in empInfo) 
           { 
               lblID.Text = v.EmployeeID.ToString(); 
               lblLoginKey.Text = v.EmployeeLoginKey.ToString(); 
               lblPassword.Text = v.passwd.ToString(); 
               lblUserName.Text = v.username.ToString(); 

            } 
       } 
       else 
       { 
           Response.Redirect("Default.aspx"); 
        } 
    } 
} 

I had used online converter converted to vb, when I compile the program, it returns an error for the following sentence:

For Each v As var In empInfo

how to convert var from c# to vb?

Upvotes: 0

Views: 530

Answers (4)

Rohit Vyas
Rohit Vyas

Reputation: 1969

Try with

foreach (Dim v in empInfo) 
                lblID.Text = v.EmployeeID.ToString()
                lblLoginKey.Text = v.EmployeeLoginKey.ToString()
                lblPassword.Text = v.passwd.ToString()
                lblUserName.Text = v.username.ToString()
 Next

Don't forget to add below lines at top of the page

Option Strict On
Option Infer On

Upvotes: 0

Christian Hayter
Christian Hayter

Reputation: 31071

For Each v In empInfo

To get VB to infer variable types, just omit the As clause, e.g.

Dim a = b + c

NOTE: This will only work when Option Infer is On. When Option Infer is Off, then variables without type specifiers will default to Object instead.

Upvotes: 0

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

Just skip type declaration: For Each v In empInfo.

You have to have Option Infer On set.

Formal For Each statement syntax is described on MSDN as following:

For Each element [ As datatype ] In group
    [ statements ]
    [ Continue For ]
    [ statements ]
    [ Exit For ]
    [ statements ]
Next [ element ]

Upvotes: 2

Mohammad Arshad Alam
Mohammad Arshad Alam

Reputation: 9862

try with this code:

For Each Dim item In empInfo

Upvotes: 0

Related Questions