创建身份证绑定数据的文本框。
代码:
<TextBlock Text="证件号:" Grid.Column="0" Grid.Row="5" />
<TextBox Grid.Column="1" Grid.Row="5" x:Name="txt_CertificateType" TextChanged="txt_CertificateType_TextChanged"/>
<TextBlock Text="性别:" Grid.Column="3" Grid.Row="5" />
<ComboBox Grid.Column="4" Grid.Row="5" x:Name="cbo_Gender" />
<TextBlock Text="年龄:" Grid.Column="0" Grid.Row="7" />
<TextBox Grid.Column="1" Grid.Row="7" x:Name="txt_Age"/>
<TextBlock Text="出生年月:" Grid.Column="3" Grid.Row="7"/>
效果图:
创建“证件号”的文本框改变事件“TextChanged="txt_CertificateType_TextChanged"”并转到定义。
后台自动创建代码:
private void txt_CertificateType_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
}
声明参数:string strIdCard = txt_CertificateType.Text.Trim();来接受页面传过来的数值。
代码:
private void txt_CertificateType_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
string strIdCard = txt_CertificateType.Text.Trim();
try
{
判断接收的数据长度是否等于18
if (strIdCard.Length == 18)
{
string keys = strIdCard;
接收截取的数据(Substring:子字符串从指定的字符位置开始且具有指定的长度)
int sex = int.Parse(keys.Substring(16, 1));
要截取的数据取余数
if (sex % 2 == 0)
{
//绑定下拉框(女)
cbo_Gender.SelectedValue = 34;
}
else
{
//绑定下拉框(男)
cbo_Gender.SelectedValue = 33;
}
//年(利用身份证号提取出生日期)(Substring:子字符串从指定的字符位置开始且具有指定的长度)
string birth_y = keys.Substring(6, 4);
//月(利用身份证号提取出生日期)(Substring:子字符串从指定的字符位置开始且具有指定的长度)
string birth_m = keys.Substring(10, 2);
//日(利用身份证号提取出生日期)(Substring:子字符串从指定的字符位置开始且具有指定的长度)
string birth_d = keys.Substring(12, 2);
ListViewItem l = new ListViewItem();
//绑定出生日期(拼接截取的数据)
dtp_Birthday.Text= birth_y + "年" + birth_m + "月" + birth_d + "日";
//获取今年年份
string strNow = DateTime.Now.Year.ToString();
//把今年转化成数字
decimal decNow = Convert.ToDecimal(strNow);
//获取(截取身份证)出生年份
decimal decbirth_y = Convert.ToDecimal(birth_y);
//获取虚岁(当前日期减去出生日期)
decimal decAge = Convert.ToDecimal(decNow - decbirth_y) + 1;
//绑定年龄
txt_Age.Text = decAge.ToString().Trim();
}
}