2013-06-22 56 views
-1

我的程序有一個主窗體,其中保存了其他子窗體的值存儲庫。出於某種原因,子表單是給我的錯誤:如何將參數從1格式傳遞給另一格式?

an object reference is required for the non-static field

這是我的主要形式有:

public partial class frm_SystemLog : Form 
{ 
    public frm_SystemLog() 
    { 
     InitializeComponent(); 
    } 

    public string TextBoxValue 
    { 
     // suppose to get value from other forms 
     get { return this.textBox1.Text; } 
     set { textBox1.Text = value; } 
    } 

    private void frm_SystemLog_Load(object sender, EventArgs e) 
    { 
     Log frm_LoginMenu = new Log(); 
     frm_LoginMenu.ShowDialog(); 
    } 
} 

這是我的子形式:

public partial class Log : Form 
{ 
    public Log() 
    { 
     InitializeComponent(); 
    } 

    private void button2_Click(object sender, EventArgs e) 
    { 
     // this is where the error happens 
     frm_SystemLog.TextBoxValue = "SomeValue"; 
     this.Close(); 
    } 
} 

回答

1

你應該在你的日誌的形式創建一個屬性,然後設置,當你訪問它

//in log form 
public String MyValue{get;set;} 

然後在你的日誌形式的BUTTON2的屬性中進行選擇的DialogResult並將其設置爲確定 然後在BUTTON2其價值單擊事件

private void button2_Click(object sender, EventArgs e) 
    { 
     MyValue = "SomeValue"; 
     //no need to close ,dialogresult will do it... 

    } 

然後在frm_SystemLog形式做到這一點

private void frm_SystemLog_Load(object sender, EventArgs e) 
    { 

     Log frm_LoginMenu = new Log(); 
     frm_LoginMenu.ShowDialog(); 
     if(frm_LoginMenu.ShowDialog() == DialogResult.OK) 
     { 
      this.TextBoxValue = frm_LoginMenu.MyValue; 
     } 

    } 

這應該可以解決您的問題。

+0

我必須創建一個觸發器變量,因爲當我回想起frm_SystemLog時,它會重新載入日誌表單...但代碼很有用。 –

0

frm_SystemLog.TextBoxValue ISN」從button2_Click可訪問,因爲它在一個不同的類。

+0

我想這就是問題所在。 ..讚賞它,但我正在尋求解決方案。 –

0

當前你正在嘗試引用父窗體類中的一個對象,而不是你的類的一個實例。在這種情況下,您可以引用的唯一對象是靜態對象,因此會出現錯誤。

您需要實際參考父窗體的實例。更改Log類,如下所示:

public partial class Log : Form 
{ 
    private frm_SystemLog parentForm; 

    public Log(frm_SystemLog parentForm) 
    { 
     InitializeComponent(); 

     this.parentForm = parentForm; 
    } 
    ... 
    ... 

然後使用實例化您的子窗體:

Log frm_LoginMenu = new Log(this); 

閱讀"Understanding Classes, Methods, and Properties in C#"更多的信息,特別是:

There are two kinds of methods in C#. They are:

  • Instance Method
  • Static Method

Instance Methods are methods declared outside the main method and can be accessed only by creating an object of the corresponding class.

Class methods also are declared outside the main method but can be accessed without creating an object of the class. They should be declared with the keyword static and can be accessed using the classname.methodname syntax.

+0

我學了很多東西,但方向並沒有解決我的問題。 –

+1

這是非常基本的東西@Henryyottabyte。我給了你修改的代碼。 *它究竟*不能解決你的問題? –

相關問題