创建Windows窗体应用程序项目experment9,向其中添加一个窗体 Forml;用一个学生纳数组存放10名学生的记录,然后根据用户指定的学号显示相应的学生记录。
时间: 2023-06-18 19:03:12 浏览: 124
用文件存储10个学生的姓名、学号、手机号、地址,可通过姓名或者学号查找
5星 · 资源好评率100%
好的,下面是完整的代码实现:
```c#
using System;
using System.Windows.Forms;
namespace experment9
{
public partial class Form1 : Form
{
// 学生记录数组
private Student[] students;
public Form1()
{
InitializeComponent();
// 初始化学生记录数组
students = new Student[10];
students[0] = new Student(1, "张三", 20, "男");
students[1] = new Student(2, "李四", 21, "女");
students[2] = new Student(3, "王五", 22, "男");
students[3] = new Student(4, "赵六", 23, "女");
students[4] = new Student(5, "钱七", 24, "男");
students[5] = new Student(6, "孙八", 25, "女");
students[6] = new Student(7, "周九", 26, "男");
students[7] = new Student(8, "吴十", 27, "女");
students[8] = new Student(9, "郑一", 28, "男");
students[9] = new Student(10, "王二", 29, "女");
}
private void button1_Click(object sender, EventArgs e)
{
// 获取用户输入的学号
int id = int.Parse(textBox1.Text);
// 根据学号查找学生记录
Student student = null;
foreach (Student s in students)
{
if (s.Id == id)
{
student = s;
break;
}
}
// 显示学生记录
if (student != null)
{
label2.Text = "姓名:" + student.Name;
label3.Text = "年龄:" + student.Age;
label4.Text = "性别:" + student.Gender;
}
else
{
MessageBox.Show("未找到该学生!");
}
}
}
// 学生类
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
public Student(int id, string name, int age, string gender)
{
Id = id;
Name = name;
Age = age;
Gender = gender;
}
}
}
```
在这个实现中,我们首先在窗体的构造函数中初始化了一个包含10名学生记录的数组。然后,在单击按钮时,我们获取了用户输入的学号,并在数组中查找相应的学生记录。最后,我们将找到的学生记录显示在窗体上,或者在未找到该学生时弹出错误提示框。
阅读全文