2012-06-24 215 views
0

我遇到了一個錯誤。儘管聲明變量(failturetext和userName)仍然出現錯誤。誰能幫幫我嗎?使用未分配的本地變量

- Use of Unassigned local variable "FailureText" 
- Use of Unassigned local variable "UserName" 


protected void Login1_LoginError(object sender, System.EventArgs e) 
{ 
    TextBox FailureText; 
    TextBox UserName; 

    //There was a problem logging in the user 
    //See if this user exists in the database 
    MembershipUser userInfo = Membership.GetUser(UserName.Text); // errors appear here 
    if (userInfo == null) 
    { 
     //The user entered an invalid username... 
     //error appear here (failuretext.text) 
     FailureText.Text = "There is no user in the database with the username " + UserName.Text; 
    } 

感謝(:。

+4

您的代碼段包含許多可能的錯誤和錯誤。爲什麼,例如,你甚至可以創造這些可變物?我不確定這是Win Forms還是ASP.NET,但是您應該閱讀一些關於您的適當技術的教程並相應更新問題標籤 – YavgenyP

+4

同意YavgenyP - 您的問題表明您不理解C#和Winforms/Asp.Net。請參考書或教程,而不是使用SO作爲替代品。 –

回答

3

你聲明的變量,但您正在嘗試引用它們的屬性,再沒有任何分配給他們這消息的來源你有更大的問題,因爲那些代表UI控件,它們不太可能是你的函數中的局部變量,它們可能應該屬於頁面(或者表單),而不是在本地聲明。

+0

起初,代碼是: MembershipUser userInfo = Membership.GetUser(Login1.UserName); if(userInfo == null) { //用戶輸入了一個無效的用戶名... FailureText.Text =「數據庫中沒有用戶使用用戶名」+ Login1.UserName; } 並且錯誤變成 - 名稱「failureText」在當前上下文中不存在,這就是爲什麼我聲明一個局部變量。 – user1467175

+0

@ user1467175:C#區分大小寫。 'failureText'和'FailureText'是兩個不同的對象!刪除這些局部變量並改正大寫/小寫問題! –

0

關於編譯器消息 - 看看這個link

TextBox FailureText; - you declared a variable, but it is not initialized. you might set it to null/a value/default() - but you must initialize it 
TextBox UserName; - the same 

當你調用UserName.Text - 對於未初始化UserName

0

編譯器警報如果您想保留相同的約定在你的那一刻,然後去解決它失敗了,您想要編譯的問題在嘗試引用它們之前先將兩個變量分配一個空值。

像這樣:

TextBox FailureText = null; 
TextBox UserName = null; 

如果你這樣做,你可能需要檢查,當你嘗試和分配這些對象的屬性,他們是否仍然空。

正如上面的人所說,你不應該這樣做,因爲UI控件應該始終是形式本身的全局。

相關問題