按钮事件的统一处理
文章目錄
- 1 按鈕事件的統一處理
- 1.1 項目UI及所需實現的功能簡要介紹
- 1.2 功能實現
1 按鈕事件的統一處理
1.1 項目UI及所需實現的功能簡要介紹
項目UI如下:
所需實現的功能:
1.2 功能實現
首先來看下實體類的代碼,非常簡單:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace xiketang.com.WinformBase {/// <summary>/// 課程實體類/// </summary>public class Course{public Course() { }public Course(int courseId, string courseName, int classHour, string teacher){this.CourseId = courseId;this.CourseName = courseName;this.ClassHour = classHour;this.Teacher = teacher;}public int CourseId { get; set; }public string CourseName { get; set; }public int ClassHour { get; set; }//課時public string Teacher { get; set; }//主講老師} }窗體相關代碼如下:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms;namespace xiketang.com.WinformBase {public partial class FrmEventApp : Form{//用來封裝課程對象的容器private List<Course> courseList = new List<Course>();public FrmEventApp(){InitializeComponent();//多個按鈕響應同一個事件,在此做事件關聯//this.btn01.Click += new System.EventHandler(this.btn_Click);//this.btn02.Click += new System.EventHandler(this.btn_Click);//this.btn03.Click += new System.EventHandler(this.btn_Click);//this.btn04.Click += new System.EventHandler(this.btn_Click);//this.btn05.Click += new System.EventHandler(this.btn_Click);//this.btn06.Click += new System.EventHandler(this.btn_Click);//this.btn07.Click += new System.EventHandler(this.btn_Click);//this.btn08.Click += new System.EventHandler(this.btn_Click);//this.btn09.Click += new System.EventHandler(this.btn_Click);//this.btn10.Click += new System.EventHandler(this.btn_Click);//this.btn11.Click += new System.EventHandler(this.btn_Click);//this.btn12.Click += new System.EventHandler(this.btn_Click);//以上方法,如果你這么寫程序,會被別人認為你什么都不懂!foreach (Control item in this.Controls){//if (item is Button)//通過控件類型過濾我們不需要的控件//{// Button btn = item as Button;// if (btn.Tag.ToString() != "Save")//過濾我們不需要的按鈕,請大家特別注意Tag的使用// {// btn.Click += new System.EventHandler(this.btn_Click);// }//}if (item is Button && item.Tag.ToString() != "Save"){item.Click += new System.EventHandler(this.btn_Click);}}}//事件集中處理方法private void btn_Click(object sender, EventArgs e){Button btn = sender as Button;//將當前按鈕Tag屬性中封裝的課程信息,通過字符串分割得到string[] info = btn.Tag.ToString().Split(',');//將當前課程信息封裝到課程對象,并將課程對象封裝到集合中this.courseList.Add(new Course{CourseName = btn.Text,CourseId = Convert.ToInt32(info[0]),ClassHour = Convert.ToInt32(info[1])});//改變當前按鈕的背景色btn.BackColor = Color.Green;//請大家思考:如果避免用戶多次添加同一個課程按鈕,而導致多次添加的問題...}//保存所選課private void btnSave_Click(object sender, EventArgs e){//實際開發中,保存可以到數據庫、文件...//測試看看所選擇的課程foreach (var item in this.courseList){Console.WriteLine(item.CourseId+"\t"+item.ClassHour+"\t"+item.CourseName);}}} }參考資料:
總結
- 上一篇: 重装电脑系统怎么做 电脑重装系统操作指南
- 下一篇: 用u盘装系统怎么会恢复失败 u盘装系统恢