C#練習建立簡易輸入介面(運用constructor、運用Parse取textBox值、提取當下年分)

建立一個簡單的輸入介面並且列印出來,對初學的我有一些挑戰,弄了1個小時終於弄出來了,對於老手來說沒甚麼,但對於我卻很有成就感呢。
簡易輸入介面
介面運用物件:
button
label
textBox
numericUpDown

在撰寫過程中遇到兩個問題,在下方程式碼用紅色標示出來。
1.計算年齡須取得當下年分,再減去出生年分。
2.出生年分運用textBox輸入方式轉成int值後傳遞至student物件。

解決方式:
1.運用Parse判斷取值於textBox。int YYYY = Int32.Parse(textBox3.Text);】
2.運用DateTime.now.year取得當下年分。year = DateTime.Now.Year - yy;】
專案主程式:
public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int YYYY = Int32.Parse(textBox3.Text);
            student a = new student(textBox1.Text,textBox2.Text,YYYY,(int)UpDown1.Value,(int)UpDown2.Value);

            MessageBox.Show(a.check(),"資料預覽");
        }
    }


物件程式碼:
class student
    {
        public int yy, mm, dd, year;
        public string name, id;

        public student(string NAME, string ID, int YY, int MM, int DD)
        {
            name = NAME;
            id = ID;
            yy = YY;
            mm = MM;
            dd = DD;
            year = DateTime.Now.Year - yy;

        }
        public string check()
        { 
            return "Name: " + name + "\r\nID Number: " + id + "\r\n出生日期: " + yy + "年" + mm + "月" + dd + "日" +
                "\r\n年齡: " + year;
        }
    }


常常聽到:不會?查啊~~
真的!自己找出答案與解決方式後會比較有印象,學習效果也較好。

留言