2010-04-23 50 views
0
public class Account 
     { 
      public string Username 
      { 
       get { return Username; } 
       set { Username = value; } 
      } 
     } 


public class ListAcc 
     { 
      static void Data() 
      { 
       List<Account> UserList = new List<Account>(); 
       //example of adding user account 
       Account acc = new Account(); 
       acc.Username = textBox1.Text; //error 
       UserList.Add(acc); 
      } 
     } 

訪問textBox1.Text時出現錯誤? (非靜態字段,方法或屬性需要對象引用...有人可以提供幫助嗎?將文本框添加到列表中! c#

但如果代碼是:

private void textBox1_TextChanged(object sender, EventArgs e) 
    { 
      List<Account> UserList = new List<Account>(); 
      //example of adding user account 
      Account acc = new Account(); 
      acc.Username = textBox1.Text; 
      UserList.Add(acc); 
    } 

它的工作!有人可以幫助我解決我的錯誤?非常感謝!

回答

3

TextBox1是無法在靜態方法中訪問的成員變量。 您可以獲得如下代碼。

public class ListAcc 
{ 
      private static List<Account> UserList; 
      public static List<Account> Data() 
      { 
       return UserList; 
      } 
     } 
private void textBox1_TextChanged(object sender, EventArgs e) 
    { 
      UserList = new List<Account>(); 
      //example of adding user account 
      Account acc = new Account(); 
      acc.Username = textBox1.Text; 
      UserList.Add(acc); 
    } 
2

注意,Data方法是靜態的,textBox1_TextChanged不是。 textBox1是一個實例變量,它屬於您的類的特定實例。 static方法屬於類本身,並且不能看到實例變量。 static方法不知道要與哪個實例交談。

爲什麼你想Data方法是static

0

無法使用對象的引用(例如form1.TextBox1),您無法從靜態方法訪問對象的字段/屬性/方法(在本例中爲容器對象的textBox1,例如WinForm對象)。 TextBox1在您的容器對象例如form1中也可能是私有的,所以您將無法在ListAcc對象的form1對象之外訪問它。

下面是一些應該工作的示例代碼。

public class ListAcc 
{ 
    // Don't put this in Data or you'll recreate it again and 
    // again when you call Data 
    private static List<Account> UserList = new List<Account>(); 

    // We'll pass in textBox1.Text via name parameter instead of 
    // referencing it directly which we can't 
     public static void Data(string name) 
     { 
      //example of adding user account 
      Account acc = new Account(); 
      acc.Username = name; 
      UserList.Add(acc); 
     } 
} 

private void textBox1_TextChanged(object sender, EventArgs e) 
{ 
    // We'll call Data and pass in textBox1.Text as our UserName 
    ListAcc.Data(textBox1.Text); 
} 

注意TextChanged事件不完全是把你的數據的方法,因爲它每次擡起你進入一個新的字符/按Backspace鍵/等的最佳場所。

+0

是的,我認爲是的!那麼,在所有文本框中獲取完整字符串的最佳方法是什麼? – 2010-04-23 07:40:13

+0

使用按鈕並處理該按鈕的單擊事件以獲取每個TextBox中的文本並調用Data方法。 For循環將很好地工作。 – anonymous 2010-04-23 07:53:20

0

textBox1是對象變量,它們屬於對象,因此您需要在使用它之前創建ListAcc類的對象(實例)。

無效數據()是靜態方法屬於不反對,這意味着你可以使用,而不必創建它的實例。

從你的源代碼中你嘗試在靜態方法中使用textBox1(它必須屬於對象),這是不合理的。您可以通過刪除靜態關鍵字或從此方法刪除textBox1來解決此問題。

相關問題