首页 > 解决方案 > 如何通过数据表计算年龄

问题描述

我正在做一个项目来保存大象的详细信息,然后当它们死去时,我需要计算它们的年龄并将其显示在文本框中。为了检索给定大象的已保存生日,我使用了一个数据表。然后,我打算通过从当前年份中减去出生年份来找到年龄。

这是代码:

String elid = cmbidentyno.SelectedItem.ToString();
con.Open();

String select_query = "SELECT ElephantName,DOBirth FROM ElephantData WHERE ElephantID='" + elid + "'";
cmd = new SqlCommand(select_query, con);

SqlDataReader R = cmd.ExecuteReader();

while (R.Read())
{
    txtelname.Text = R.GetValue(0).ToString();
    DateTime now = DateTime.Today;
    DateTime birth = DateTime.R.GetValue(2);
    int age = now.Year - birth.Year;
    txtdesage.Text = age.ToString();
}

elid = cmbidentyno.SelectedItem.ToString();
con.Close();

但这不起作用。有解决方案吗?

标签: sql.net

解决方案


...
DateTime birth = DateTime.R.GetValue(2);
...

DateTime里面没有R财产。

如果你想阅读DateTime使用GetDateTime(). 因此,代码中的问题行变为:

...
DateTime birth = R.GetDateTime(2);
...

推荐阅读