C# 从类对象获取数据
我正在尝试从一个对象获取数据,我正在创建的程序目前包含3个按钮:C# 从类对象获取数据,c#,wpf,C#,Wpf,我正在尝试从一个对象获取数据,我正在创建的程序目前包含3个按钮: set(在文本框中设置数据并创建新的Student) 清除(清除提及的文本框) 获取 我在get方面遇到了问题,因为它涉及到在数据被清除后恢复数据,这需要从newstudent获取数据,我不太确定如何做到这一点 编辑:我还应该添加,student是一个单独的类,我从您的newStudent变量创建此数据,该变量仅存在于btnSet\u Click函数的范围内。您可能希望在btnGet\u Click函数中使用类变量访问newStu
set
(在文本框中设置数据并创建新的Student
)清除
(清除提及的文本框)获取
李>
我在get
方面遇到了问题,因为它涉及到在数据被清除后恢复数据,这需要从newstudent
获取数据,我不太确定如何做到这一点
编辑:我还应该添加,student是一个单独的类,我从您的
newStudent
变量创建此数据,该变量仅存在于btnSet\u Click函数的范围内。您可能希望在btnGet\u Click函数中使用类变量访问newStudent
实际上,我不确定你的首要目标是什么,我猜你想在学生从其他地方创建之后重用它。然后使用属性而不是局部变量:
private void btnset_Click(object sender, RoutedEventArgs e)
{
Student newstudent = new Student();
{
newstudent.Forename = txtforename.Text;
newstudent.Surname = txtsurname.Text;
newstudent.Course = txtcourse.Text;
newstudent.DoB = txtdob.Text;
newstudent.Matriculation =int.Parse(txtmatric.Text);
newstudent.YearM = int.Parse(txtyearm.Text);
}
}
现在,您也可以从其他事件处理程序访问该对象。在类中声明一个变量以保存
学生数据,如下所示:
private Student NewStudent { get; set; }
private void btnset_Click(object sender, RoutedEventArgs e)
{
NewStudent = new Student();
NewStudent.Forename = txtforename.Text;
NewStudent.Surname = txtsurname.Text;
NewStudent.Course = txtcourse.Text;
NewStudent.DoB = txtdob.Text;
NewStudent.Matriculation = int.Parse(txtmatric.Text);
NewStudent.YearM = int.Parse(txtyearm.Text);
}
Student theStudent;
“set”方法中的Student
的new
初始化将负责创建和存储Student
对象的数据
现在,在“获取”按钮的单击处理程序中,您可以获取学生的值,如下所示:
private Student NewStudent { get; set; }
private void btnset_Click(object sender, RoutedEventArgs e)
{
NewStudent = new Student();
NewStudent.Forename = txtforename.Text;
NewStudent.Surname = txtsurname.Text;
NewStudent.Course = txtcourse.Text;
NewStudent.DoB = txtdob.Text;
NewStudent.Matriculation = int.Parse(txtmatric.Text);
NewStudent.YearM = int.Parse(txtyearm.Text);
}
Student theStudent;
学生名和新学生姓的组合看起来很奇怪。那不可能是对的。看起来你在寻找绑定
。WPF
的美妙之处在于能够绑定到数据,并且GUI可以通过数据进行更新。不,你是对的,我正在尝试各种方法来获取数据。你需要考虑你的变量范围newstudent只存在于你的bntset_click方法中。不一定,添加一个SaveStudent(newstudent)
在最后调用,然后作用域就可以了。@JoshuaAiroConlinTaylor:然后通过分配new Student()
给它一个默认值。或者在访问它时检查它是否为null。