- 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;
- namespace 課程選擇
- {
- public partial class Form1 : Form
- {
- private int totalHours = 0;
- public Form1()
- {
- InitializeComponent();
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- 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) };
- for (int i = 0; i < 8; i++)
- {
- comboBox1.Items.Add(courses[i]);
- }
- textBox1.Text = "0";
- }
- private void btnAdd_Click(object sender, EventArgs e)
- {
- if (comboBox1.SelectedIndex != -1)//判斷是否選擇了課程
- {
- Course c1 = (Course)comboBox1.SelectedItem;
- if (!listBox1.Items.Contains(c1))//若是listBox1中不包括選擇的課程
- {
- listBox1.Items.Add(c1);//添加到listBox1中
- totalHours += c1.hours;//學時隨之增長
- textBox1.Text = totalHours.ToString();//顯示到textBox1中
- }
- }
- }
- private void btnDelete_Click(object sender, EventArgs e)
- {
- if (listBox1.SelectedIndex != -1)//判斷是否選擇了課程
- {
- Course c1 = (Course)listBox1.SelectedItem;
- listBox1.Items.Remove(c1);//從listBox1中清除
- totalHours -= c1.hours;//學時隨之減小
- textBox1.Text = totalHours.ToString();
- }
- }
- }
- public class Course
- {
- public string name;//課程名
- public int hours;//學時
- public Course(string name, int hours)
- {
- this.name = name;
- this.hours = hours;
- }
- public override string ToString()
- {
- return name;
- }
- }
- }