我在 C# 和这个网站上相对较新。
我目前正在尝试制作这个应用程序来存储员工的数据(例如姓名、姓氏、身份证号码、薪水)并根据命令显示所选员工的数据。
我的问题是我不知道要创建什么样的类,如何构建它以及每次单击“保存按钮”创建该类的新实例时如何调用它,该实例将保存从中提取的数据表单的文本框。
我在论坛上搜索过,并设法在表单中写下了这个:
private void button1_Click(object sender, EventArgs e) {
Employee newemployee = new Employee();
{
string fname = textBox1.Text;
string sname = textBox2.Text;
string id = textBox3.Text;
string sal = textBox4.Text;
label5.Text = fname;
label6.Text = sname;
label7.Text = id;
label8.Text = sal;
}
}
类中的这个:
public class Employee {
public string fname { get; set; }
public string sname { get; set; }
public string id { get; set; }
public string sal { get; set; }
}
但当然,这个类根本没有被使用(显然是因为它还没有完成),标签直接打印在文本框中。
注意:我把标签放在那里是为了在这个过程中测试类。
最佳答案
在您的类中,您已经创建了字符串值,这些值将在您创建类的实例时创建:
Employee newemployee = new Employee();
这会为类中声明的所有变量创建内存空间
public class Employee
{
public string fname { get; set; }
public string sname { get; set; }
public string id { get; set; }
public string sal { get; set; }
}
你正在做的是创建额外的字符串:
string fname = textBox1.Text;
string sname = textBox2.Text;
string id = textBox3.Text;
string sal = textBox4.Text;
因此,当您初始化类时,它会创建您应该用于该类实例的变量。以下代码表示类的初始化并使用示例代码中的变量:
Employee newemployee = new Employee();
newemployee.fname = textBox1.Text;
newemployee.sname = textBox2.Text;
newemployee.id = textBox3.Text;
newemployee.sal = textBox4.Text;
label5.Text = newemployee.fname;
label6.Text = newemployee.sname;
label7.Text = newemployee.id;
label8.Text = newemployee.sal;
希望对您有所帮助,它解释了您哪里出错了。
关于C# 如何创建一个类来存储来自文本框的字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49751595/