2016-12-17 21 views
0

我搜索了很多,但我沒有找到一個有效的答案。這就是我想要的。獲取一個表格的textbox.text

我有一個帶有文本框的窗口。當我按下按鈕時,我創建了一個類的實例,然後我想將te textbox.text讀入類中。 這是我的嘗試:

文本框離開事件(Name文本= textBox_klantnaam):

klantNaam = textBox_klantnaam.Text; 

在相同的形式,我有一個屬性:

public string klantNaam 
{ 
    get { return textBox_klantnaam.Text; } 
    set { textBox_klantnaam.Text = value; } 
} 

的onclick按鈕:

private void button1_Click(object sender, EventArgs e) 
{ 
    Class_licentiemanager SchrijfLicentieBestand = new Class_licentiemanager(); 
    SchrijfLicentieBestand.schrijfLicBestand(); 
} 

需要讀取textbox.text然後將其寫入fi的類le 財產「klantNaam」似乎是空的?

namespace Opzet_Leeg_Framework 
{ 
    class Class_licentiemanager 
    { 
     Class_Logging logging = new Class_Logging(); 
     public static Form_Licentiemanager Licentiemanager = new Form_Licentiemanager(); 

     public void schrijfLicBestand() 
     { 

      using (StreamWriter w = new StreamWriter(Settings.applicatiePad + Form1.SettingsMap + Form1.Applicatienaam + ".lic")) 
       try 
       { 
        try 
        { 
         w.WriteLine("test line, works fine"); 
         w.WriteLine("Naam klant : " + Licentiemanager.klantNaam); //Empty , no line ??? 
        } 
        catch (Exception e) 
        { 
         logging.witeToLog("FOUT", "Het opslaan van het licentiebestand is mislukt", 1); 
         logging.witeToLog("FOUT", "Melding : ", 1); 
         logging.witeToLog("FOUT", e.ToString(), 1); 
        } 
       } 
       finally 
       { 
        w.Close(); 
        w.Dispose(); 
       } 
     } 
    } 
} 

回答

2

您需要將該值傳遞給該類,而不是在其中創建另一個表單實例。當您編寫new Form_Licentiemanager時,您將創建該表單的新實例並且不會重複使用同一個實例,因此該新實例上的值仍爲空。爲了解決這個問題,請執行下列操作:

private void button1_Click(object sender, EventArgs e) 
{ 
    Class_licentiemanager SchrijfLicentieBestand = new Class_licentiemanager(); 
    SchrijfLicentieBestand.schrijfLicBestand(klantNaam); 
} 

,改變你的代碼:

class Class_licentiemanager 
{ 
    Class_Logging logging = new Class_Logging(); 
    public void schrijfLicBestand(string klantNaam) 
    { 
     // same code here ...... 
        w.WriteLine("test line, works fine"); 
        w.WriteLine("Naam klant : " + klantNaam); 
     // same code here ...... 
    }   
} 
+0

非常感謝,這個工程。 – Hansvb

相關問題