1.设计一个窗体程序,定义一个Teacher类,包含姓名和职称两个字段和一个输出自己信息的方法,并用ArrayList实现与对集合的增、删、插入和遍历功能。
设计如下界面:
编写代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections; //引入命名空间
namespace 教师
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
label4.Text = "";
}
ArrayList a = new ArrayList();
public void display()
{
foreach(object t in a)
{
Teacher x = (Teacher)t;
label4.Text += "\n" + x.ShowMsg();
}
}
//添加到末尾
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "" && textBox2.Text != "")
{
Teacher x = new Teacher(textBox1.Text, textBox2.Text);
a.Add(x);
label4.Text = "";
display();
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
}
else
{
MessageBox.Show("请输入完整的信息进行添加!!");
}
}
//遍历
private void button3_Click(object sender, EventArgs e)
{
if (a.Count != 0)
{
label4.Text = "";
display();
}
else
{
MessageBox.Show("没有教师信息!");
}
}
//插入到
private void button2_Click(object sender, EventArgs e)
{
try
{
Teacher t = new Teacher(textBox1.Text, textBox2.Text);
a.Insert(Convert.ToInt32(textBox3.Text), t);
label4.Text = "";
display();
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
}
catch
{
MessageBox.Show("请输入完整信息");
}
}
//删除
private void button4_Click(object sender, EventArgs e)
{
try
{
if (a.Count != 0)
{
a.RemoveAt(Convert.ToInt32(textBox3.Text));
label4.Text = "";
display();
}
else
{
MessageBox.Show("没有教师信息!");
}
}
catch
{
MessageBox.Show("请正确输入信息");
}
}
}
public class Teacher
{
string name;
string title;
public Teacher(string name,string title)
{
this.name =name;
this.title =title;
}
public string ShowMsg()
{
return string.Format ("姓名:{0},职称:{1}",name,title);
}
}
}
运行结果: