C# 如何创建一个类来存储来自文本框的字符串值

标签 c# winforms

我在 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/

相关文章:

c# - 更换按钮位置

C# 程序崩溃 comboBox SelectedItem ToString

c# - 替换是/否/取消 MessageBox (C#)

c# - 将自定义上下文菜单项添加到 Windows 窗体标题栏

c# - 如何将某些颜色分类到颜色范围?

c# - 如何在 mvvmcross View 模型中使用异步?

c# - 从 Excel 中检索 "row pairs"

c# - 当另一个关闭时显示最小化的形式

c# - 551 发件人地址对您的登录无效

c# wpf MVVM 从 ObservableDictionary 获取 ObservableList