要求:
軟件上有一張圖片,默認是隱藏的。用戶在文本框中輸入身份證號(131226198105223452),點擊按鈕,如果年齡大於18歲,則顯示圖片。
知識點:
取當前年份,Date Time Now Year
所需用到的函數函數一:
string string.Substring(int startIndex,int length)(+1重載)
從此實例檢索字符串。子字符串從指定的字符位置開始且具有指定的長度
異常:
System.ArgumentOutOfRangeException函數二:
int Convert.toInt32(string value)(+18重載)
將數字的指定 System.String 表示形式轉換為等效的32位有符號整數
異常:
System.FormatException
System.OverflowException函數三:
struct System.DateTime
表示時間的一刻,通常以日期和當天的時間表示。
源碼如下:
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 { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string 身份證號 = textBox1.Text; /* string string.Substring(int startIndex,int length)(+1重載) * 從此實例檢索字符串。子字符串從指定的字符位置開始且具有指定的長度 * * 異常: * System.ArgumentOutOfRangeException */ string strYear=身份證號.Substring(6,4); /* int Convert.toInt32(string value)(+18重載) * 將數字的指定 System.String 表示形式轉換為等效的32位有符號整數 * 異常: * System.FormatException * System.OverflowException */ int year = Convert.ToInt32(strYear); /* struct System.DateTime * 表示時間的一刻,通常以日期和當天的時間表示。 */ if (DateTime.Now.Year - year > 18) { pictureBox1.Visible = true; } else { pictureBox1.Visible = false; } } } }
運行截圖: