using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace MySchool
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
List<Student> allstudent = new List<Student>();
//建立集合
private void btnsearch_Click(object sender, EventArgs e)
{
Student s1 = new Student("张三", 18, "男");
Student s2 = new Student("刘德华", 50, "男");
Student s3 = new Student("周星驰", 40, "男");
Student s4 = new Student("周杰伦", 30, "男");
allstudent.Add(s1);
allstudent.Add(s2);
allstudent.Add(s3);
allstudent.Add(s4);
AddAllStdent();
}
//显示信息
public void AddAllStdent()
{
//循环遍历所有集合中对象,添加到控件中,
//在循环中实例化listviewitem对象,添加一个信息
livxinxi.Items.Clear();//清空控件
foreach(Student stu in allstudent)
{
//添加项
ListViewItem item = new ListViewItem(stu.Name);
item.SubItems.Add(stu.Age.ToString());
item.SubItems.Add(stu.Sex);
livxinxi.Items.Add(item);
}
}
//添加一个元素
private void btnadd_Click(object sender, EventArgs e)
{
try
{
Student s1 = new Student("张三丰", 20, "男");
allstudent.Add(s1);
AddAllStdent();
}
catch
{
}
}
//删除一个元素
private void btnclear_Click(object sender, EventArgs e)
{
try
{
int index = livxinxi.SelectedItems[0].Index;
allstudent.RemoveAt(index);
AddAllStdent();
}
catch
{
}
}
//弹出消息框
private void livxinxi_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
int index = livxinxi.SelectedItems[0].Index;
MessageBox.Show(allstudent[index].SayHi());
}
catch
{
}
}
}
}