2012-04-30 42 views
0

在C#中使用基本表單應用程序時,無法訪問其中的變量。訪問表單變量

因此,與在窗體類我有

public partial class pingerform : Form 
{ 
    .. 
    .. 

    private System.Windows.Forms.TextBox textBox2; 

    public string textBox2Text 
    { 
     get { return textBox2.Text; } 
     set { textBox2.Text = value; } 
    } 

然後在主應用程序,我有

Application.Run(new pingerform()); 
... 
... 

pingerform.textBox2Text.text() = str; 

,但據我所知,沒有對象的引用。

錯誤1
是所必需的非靜態字段, 方法或屬性的對象引用 'pingerform.textBox2Text.get' C:\用戶\ aaron.street \文件\視覺 工作室11 \ Projects \ PingDrop \ PingDrop \ Program.cs 54 21 PingDrop

所以我認爲我會讓平格窗體類靜態,但它不會讓我這樣做?

錯誤1
無法創建靜態類的實例 'PingDrop.pingerform' C:\用戶\ aaron.street \文檔\ Visual Studio的 11周\項目\ PingDrop \ PingDrop \的Program.cs 21 29 PingDrop

如何訪問表單屬性與出創建窗體的特定實例,

我有一個後臺線程運行,我想定期更新的形式提交文本?

乾杯

亞倫

回答

0

你別無選擇,只能創建新實例,或者把它作爲參數傳遞給線程,或將其存儲爲您的主程序類的成員。

第二種選擇

例子:

private static pingerform myPingerform = null; 
static void Main() 
{ 
    Application.EnableVisualStyles(); 
    Application.SetCompatibleTextRenderingDefault(false); 
    myPingerform = new pingerform(); 
    Thread thread = new Thread(new ThreadStart(UpdateTextBox)); 
    thread.Start(); 
    Application.Run(myPingerform); 
} 

private static void UpdateTextBox() 
{ 
    while (true) 
    { 
     myPingerform.textBox2.Text = DateTime.Now.Ticks.ToString(); 
     Thread.Sleep(1000); 
    } 
} 

而且不要忘記改變文本框是public

注意:這是一個簡單的工作解決方案,一個後臺線程訪問文本框的簡單情況。如果你有更多的線程訪問它,這將打破。要獲得需要更多工作的最佳實踐方法,請撥打read this

+0

這會打破。 – wRAR

+0

這是否被認爲是最佳實踐,創建一個窗體的明確實例。那麼爲什麼在Visual Studio中創建模板時使用的方法不這樣做。 – DevilWAH

+0

@DevilWAH這是唯一可能的做法(除了VB或其他瘋狂) – wRAR

0

,而不產生例如,你不能訪問一個實例的屬性,它是廢話(或VB這是一樣的)。並且您已經創建了您隨後傳遞給Application.Run()的實例。無論如何,您無法在Application.Run()之後對錶單執行任何操作,因爲只有在應用退出時它纔會返回。如果你想用表格做任何事情,你需要在其他地方做這件事。當然,由於您需要創建實例,因此您無法將表單類設爲靜態。

如果您需要使用另一個線程中的表單執行某些操作,則需要在創建表單實例時將該表單實例傳遞給該線程。請注意,直接搞亂來自非GUI線程的GUI元素是一個壞主意,你應該使用Control.BeginInvoke()

-1

請試試這個:

pingerform myForm = new pingerform();  
Application.Run(myForm); 
myForm.textBox2Text = "this is text"; 
+0

'Run()'方法被阻塞。 –

+0

但正確的是,在這一點上,我需要創建一個我的表單實例。另外當更新表單的進程在seprerate線程中運行時,它是否仍然被阻塞?不說使用Run是前進的方向。但只是想知道:) – DevilWAH

+0

@DevilWAH運行你的應用程序,你必須使用'Run()'它是基本的。 –