2012-04-13 19 views
1

好吧我有一些VB代碼,我登錄,我希望它現在在C#中工作。我認爲這會很直接,但我錯了。該行:字符串connString = ConfigurationManager.ConnectionStrings(「MyConnection」)。ConnectionString;在ConnectionStrings拋出一個錯誤,我不明白爲什麼。同樣在while語句中,objDR表示它是一個變量,但正被用作一種方法。任何幫助都會很棒。以下是整個代碼:從VB.NET到C#的轉換問題我的登錄

Using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Configuration; 


public partial class _Default : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 

    } 


    protected void 
    btnSubmit_Click(object sender, System.EventArgs e) 
    { 



     if (((string.IsNullOrEmpty(txtUserName.Text)))) 
     { 
      lblErrorMessage.Text = "Username must be entered."; 

      txtUserName.Focus(); 

      return; 

     } 



     string connString = ConfigurationManager.ConnectionStrings("MyConnection").ConnectionString; 



     System.Data.SqlClient.SqlConnection myConnection = new System.Data.SqlClient.SqlConnection(connString); 

     string sql = "Select * From TCustomers"; 



     System.Data.SqlClient.SqlDataReader objDR = default(System.Data.SqlClient.SqlDataReader); 

     System.Data.SqlClient.SqlCommand objCmd = new System.Data.SqlClient.SqlCommand(sql, myConnection); 

     myConnection.Open(); 


     objDR = objCmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection); 



     bool blnLogin = false; 



     string strPassword = null; 

     string strUserName = null; 



     strPassword = txtPassword.Text; 

     strPassword = strPassword.Trim(); 

     strUserName = txtUserName.Text; 

     strUserName = strUserName.Trim(); 




     while (objDR.Read()) 
     { 

      if (((objDR("strUserName").ToString().Trim() == strUserName)) & ((objDR("strPassword").ToString().Trim() == strPassword))) 
      { 


       blnLogin = true; 


       Session["CustomerID"] = objDR("intCustomerID"); 

       Session["UserName"] = objDR("strUserName"); 

       Session["FirstName"] = objDR("strFirstName"); 

       Session["LastName"] = objDR("strLastName"); 

       Session["Email"] = objDR("strEmailAddress"); 

       Session["UserType"] = objDR("intUserTypeID"); 





       break; // TODO: might not be correct. Was : Exit While 



      } 



     } 

    } 
} 
+3

什麼是錯誤! – 2012-04-13 15:45:41

+0

'objDR(」strUserName「)。'甚至不是有效的C# – 2012-04-13 15:47:26

回答

4

在VB中,有一個方法調用或一個數組訪問之間沒有語法差異,他們都使用(argument)。但在C#中,數組使用[]。這是不正確轉換自動/死記硬背的轉換,因爲這是不可能分辨出來,所以你必須自己解決這個問題:

ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString; 
            ^   ^convert to [] array access 

同樣的,訪問的DataRow的屬性:

objDR["strUserName"] 
    ^   ^Convert to [] array access 
0

的我在你的代碼中發現的第一個問題是:

objDR("strUserName") 

您需要使用

objDR["strUserName"] 

變化從括號所有出現括號

這解釋了與「objDR錯誤說,它是一個變量,但被用作一個方法。 「