C#——设计一个窗体程序,定义一个Teacher类,包含姓名和职称两个字段和一个输出自己信息的方法,并用ArrayList实现与对集合的增、删、插入和遍历功能,实现与实例6-1相同的功能。
界面设计
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Collections; //注意对命名空间的使用
namespace WindowsFormsApp10
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
ArrayList teachers = new ArrayList(); //创建一个拥有默认初始容量的ArrayList集合
private void btnAdd_Click(object sender, EventArgs e) //添加到集合的末尾
{
Teacher x = new Teacher(txtName.Text, txtTitle.Text);
teachers.Add(x); //添加
lblShow.Text = " ";
display(); //遍历输出
}
private void display() //遍历集合并输出
{
foreach (object x in teachers)
{
Teacher t = (Teacher)x;
lblShow.Text += "\n" + t.GetMessage();
}
}
public class Teacher //定义Teacher类
{
private string title;
private string name;
public Teacher(string name, string title)
{
this.name = name;
this.title = title;
}
public string GetMessage()
{
return string.Format("姓名:{0}\n职称:{1}",this.name,this.title);
}
}
private void btnForeach_Click(object sender, EventArgs e) //遍历
{
lblShow.Text = " ";
display(); //遍历输出
}
private void btnInsert__Click(object sender, EventArgs e) //插入到指定的索引处
{
int index = Convert.ToInt32(txtIndex.Text);
Teacher x = new Teacher(txtName.Text, txtTitle.Text);
teachers.Insert(index, x); //插入
lblShow.Text = " ";
display(); //遍历输出
}
private void btnDelete__Click(object sender, EventArgs e) //删除指定索引中的元素
{
int index = Convert.ToInt32(txtIndex.Text);
teachers.RemoveAt(index); //删除
lblShow.Text = " ";
display(); //遍历输出
}
}
}