我是C#的新手,我遇到了问题。实际上这是我在大学和编程的第一年,我有阵列的问题。我在Windows Form Application中创建了一个包含3个构造函数和1个方法的类。问题是我想使用按钮将来自三个文本框的数据(用户正在键入)存储到10的数组中。而且我不知道该怎么做。
public class Employee
{
private int idnum;
private string flname;
private double annual;
public Employee()
{
idnum = 0;
flname = "";
annual = 0.0;
}
public Employee(int id, string fname)
{
idnum = id;
flname = fname;
annual = 0.0;
}
public Employee(int id, string fname, double ann)
{
idnum = id;
flname = fname;
annual = ann;
}
public int idNumber
{
get { return idnum; }
set { idnum = value; }
}
public string FLName
{
get { return flname; }
set { flname = value; }
}
public double Annual
{
get { return annual; }
set { annual = value; }
}
public string Message()
{
return (Convert.ToString(idnum) + " " + flname + " " + Convert.ToString(annual));
}
}
答案 0 :(得分:1)
首先,您应该在此表单上添加3个textboxe元素,并以下一个方式命名textBoxId,textBoxFLName,textBoxAnnual
此外,您还必须添加一个按钮。我们称之为btnSave 为此按钮编写一个事件OnClick。在这种方法中,我们必须读取用户在表单上填写的所有数据。
List<Employee> allEmployees = new List<Employee>();
private void buttonSave_Click(object sender, EventArgs e)
{
//read user input
int empId = Int32.Parse(textBoxId.Text);
string empFlName = textBoxFLName.Text;
double empAnnual = double.Parse(textBoxAnnual.Text);
// create new Employee object
Employee emp = new Employee(empId, empFlName, empAnnual);
// add new employee to container (for example array, list, etc).
// In this case I will prefer to use list, becouse it can grow dynamically
allEmployees.Add(emp);
}
您还可以用最短的方式重写代码:
public class Employee
{
public int IdNum { get; set; }
public string FlName { get; set; }
public double Annual { get; set; }
public Employee(int id, string flname, double annual = 0.0)
{
IdNum = id;
FlName = flname;
Annual = annual;
}
public override string ToString()
{
return (Convert.ToString(IdNum) + " " + FlName + " " + Convert.ToString(Annual));
}
}