地狱的镰刀
这是我们所要用的到的三个窗体
我们建一个辅助类,初始化一个单列的泛型集合,给单列的泛型集合付个初值
class Worker { private string id; private string name; private int age; private string sex; public string ID { get { return id; } set { id = value; } } public string Name { get { return name; } set { name = value; } } public int Age { get { return age; } set { age = value; } } public string Sex { get { return sex; } set { sex = value; } } public static List<Worker> list = new List<Worker>(); public static void Insert() { Worker w1 = new Worker(); w1.ID = "20090101"; w1.Name = "王小毛"; w1.Age = 20; w1.Sex = "男"; list.Add(w1); Worker w2 = new Worker(); w2.ID = "20090102"; w2.Name = "周新雨"; w2.Age = 19; w2.Sex = "女"; list.Add(w2); }
private void FrmSecond_Load(object sender, EventArgs e) {<br>如果list没有数据就添加数据,确保调用这个窗体是,只有在没有数据时才能添加数据! if (Worker.list.Count==0) { Worker.Insert(); }<br>清除datagridview的英文列,并且绑定数据 dgvList.AutoGenerateColumns = false; dgvList.DataSource = Worker.list; }
private void btn1_Click(object sender, EventArgs e) {<br>确保一个工号只能添加一次 foreach (Worker item in Worker.list) { if (item.ID==txt01.Text) { MessageBox.Show("工号已存在!!!!"); return; } }<br>添加一个员工信息 Worker w1 = new Worker(); w1.ID = txt01.Text; w1.Name = txt03.Text; w1.Age = Convert.ToInt32(txt02.Text); w1.Sex =cob01.Text; Worker.list.Add(w1); FrmSecond fs = new FrmSecond(); this.Close(); fs.Show(); }
这是删除的代码<br>private void toolStripButton3_Click(object sender, EventArgs e) {<br>提示点击是才会删除 DialogResult result = MessageBox.Show("提示","是否删除",MessageBoxButtons.YesNo,MessageBoxIcon.Question); if(result==DialogResult.Yes) {<br> string id = dgvList.SelectedRows[0].Cells[0].Value.ToString(); //string id = dgvList.SelectedCells[0].Value.ToString();<br>如果ID和我选中的ID相等才会删除 foreach (Worker item in Worker.list) { if(item.ID==id) { Worker.list.Remove(item); break; } } } //dgvList.AutoGenerateColumns = false; dgvList.DataSource = new BindingList<Worker>(Worker.list); }