18位的身份證,前面六位代表了你戶籍所在地,第七位到第十四位代表了你的出生年月,第十五位到第十七為代表了你的性別(偶數為女,奇數為男),根據這一信息,我在系統開發的錄入員工的身份證后控件焦點轉移時根據身份證號碼獲得生日和性別。
用C#寫的代碼如下:
/// <summary>
/// 在控件驗證 textBox_IdentityCard 的 Validated事件中定義身份證號碼的合法性並根據身份證號碼得到生日和性別
/// </summary>
private void textBox_IdentityCard_Validated(object sender, EventArgs e)
{
try
{
//獲取得到輸入的身份證號碼
string identityCard = textBox_IdentityCard.Text.Trim();
if (string.IsNullOrEmpty(identityCard))
{
//身份證號碼不能為空,如果為空返回
MessageBox.Show("身份證號碼不能為空!");
if (textBox_IdentityCard.CanFocus)
{
textBox_IdentityCard.Focus();//設置當前輸入焦點為textBox_IdentityCard
}
return;
}
else
{
//身份證號碼只能為15位或18位其它不合法
if (identityCard.Length != 15 && identityCard.Length != 18)
{
MessageBox.Show("身份證號碼為15位或18位,請檢查!");
if (textBox_IdentityCard.CanFocus)
{
textBox_IdentityCard.Focus();
}
return;
}
}
string birthday = "";
string sex = "";
//處理18位的身份證號碼從號碼中得到生日和性別代碼
if (identityCard.Length == 18)
{
birthday = identityCard.Substring(6, 4) + "-" + identityCard.Substring(10, 2) + "-" + identityCard.Substring(12, 2);
sex = identityCard.Substring(14, 3);
}
//處理15位的身份證號碼從號碼中得到生日和性別代碼
if (identityCard.Length == 15)
{
birthday = "19" + identityCard.Substring(6, 2) + "-" + identityCard.Substring(8, 2) + "-" + identityCard.Substring(10, 2);
sex = identityCard.Substring(12, 3);
}
textBox_Birthday.Text = birthday;
//性別代碼為偶數是女性奇數為男性
if (int.Parse(sex) % 2 == 0)
{
this.comboBox_Sex.Text = "女";
}
else
{
this.comboBox_Sex.Text = "男";
}
}
catch (Exception ex)
{
MessageBox.Show("身份證號碼輸入有誤");
if (textBox_IdentityCard.CanFocus)
{
textBox_IdentityCard.Focus();
}
return;
}
}
