获取表单的textbox.text

时间:2016-12-17 13:06:10

标签: c#

我搜索了很多,但我没有找到有效的答案。这就是我所期待的。

我有一个带文本框的窗口。当我按下一个按钮时,我创建了一个类的实例,然后我想将te textbox.text读入该类。 这就是我的尝试:

文本框离开事件(名称textbox = 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然后将其写入文件的类 该物业" 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();
                }
        }
    }
}

1 个答案:

答案 0 :(得分: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 ......  
    }           
}