2013-07-13 48 views
1

到目前爲止,如果用戶輸入內容,我將存儲在標籤屬性中。我知道這是不對的。我如何根據用戶輸入更新變量,以便在需要使用它的任何事件中使用?將用戶輸入保存爲c#windows窗體中的變量

這是我嘗試過的很多事情之一。我甚至無法找出正確的搜索條件來搜索我需要做的解決方案。

namespace Words 
{ 
    public partial class formWords : Form 
    { 
    int x = 5; 
    int y = 50; 
    int buttonWidth = 120; 
    int buttonHeight = 40; 
    string fileList = ""; 
    string word = ""; 
    string wordFolderPath = @"C:\words\";// this is the variable I want to change with the dialog box below. 

    private void selectWordFolderToolStripMenuItem_Click(object sender, EventArgs e) 
    { 
     FolderBrowserDialog folder = new FolderBrowserDialog(); 
     if (folder.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
     { 
      string folderPath = folder.SelectedPath; 
      formWords.wordFolderPath = folderPath; 
     } 
    } 

回答

2

wordFolderPath是你的班級的公開變量(但在其外部是私人的)。這意味着您班級內的任何內容都可以自由讀取/寫入數值。

至於你的語法,你可以使用變量名或使用this.

private void DoAThing() 
{ 
    wordFolderPath = "asdf"; 
    this.wordFolderPath = "qwerty"; //these are the same 
} 

訪問內部變量時,不能使用當前類的名稱。 formWords是一種類型,而不是一個實例。

使用this的唯一好處是因爲在方法中定義具有相同名稱的變量是合法的。使用這個關鍵字確保你在談論這個班級的成員。

+0

我認爲這比以前複雜得多。謝謝。 –

2

只是改變formWords.wordFolderPath = folderPath;

wordFolderPath = folderPath;

this.wordFolderPath = folderPath;

應該解決您的問題

而且,本來應該在錯誤列表中說:「一個編譯器錯誤對象引用是非靜態字段,方法或屬性所必需的...「

如果你沒有看到你的錯誤列表,你應該打開它。

相關問題