1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Windows.Forms;  
  9.  
  10. namespace 课程选择  
  11. {  
  12.     public partial class Form1 : Form  
  13.     {  
  14.         private int totalHours = 0;  
  15.         public Form1()  
  16.         {  
  17.             InitializeComponent();  
  18.         }  
  19.  
  20.         private void Form1_Load(object sender, EventArgs e)  
  21.         {  
  22.             Course[] courses = new Course[8] { new Course("大学英语", 50), new Course("高等数学", 45), new Course("计算机基础", 30), new Course("C语言", 40), new Course("大学物理", 24), new Course("电子技术", 30), new Course("数据库设计", 45), new Course("编译原理", 55) };  
  23.             for (int i = 0; i < 8; i++)  
  24.             {  
  25.                 comboBox1.Items.Add(courses[i]);  
  26.             }  
  27.             textBox1.Text = "0";  
  28.         }  
  29.  
  30.         private void btnAdd_Click(object sender, EventArgs e)  
  31.         {  
  32.             if (comboBox1.SelectedIndex != -1)//判断是否选择了课程  
  33.             {  
  34.                 Course c1 = (Course)comboBox1.SelectedItem;  
  35.                 if (!listBox1.Items.Contains(c1))//如果listBox1中不包括选择的课程       
  36.                 {  
  37.                     listBox1.Items.Add(c1);//添加到listBox1中  
  38.                     totalHours += c1.hours;//学时随之增加  
  39.                     textBox1.Text = totalHours.ToString();//显示到textBox1中  
  40.                 }  
  41.             }  
  42.         }  
  43.  
  44.         private void btnDelete_Click(object sender, EventArgs e)  
  45.         {  
  46.             if (listBox1.SelectedIndex != -1)//判断是否选择了课程  
  47.             {  
  48.                 Course c1 = (Course)listBox1.SelectedItem;  
  49.                 listBox1.Items.Remove(c1);//从listBox1中清除  
  50.                 totalHours -= c1.hours;//学时随之减少  
  51.                 textBox1.Text = totalHours.ToString();  
  52.             }  
  53.         }  
  54.  
  55.     }  
  56.     public class Course  
  57.     {  
  58.         public string name;//课程名  
  59.         public int hours;//学时  
  60.  
  61.         public Course(string name, int hours)  
  62.         {  
  63.             this.name = name;  
  64.             this.hours = hours;  
  65.         }  
  66.  
  67.         public override string ToString()  
  68.         {  
  69.             return name;  
  70.         }  
  71.     }  
  72. }