"指定的演员表无效?"

时间:2015-02-28 06:44:36

标签: c# visual-studio-2012

我有一个用c#编写的代码,我想比较两个" date"值。

第一个值来自数据库,第二个值是字符串。

我已经尝试将它们转换为日期,但这是我一直得到的错误

enter image description here

如果答案看起来那么明显,请耐心等待......我是c#的新手


string a, b;
            label32.Text = DateTime.Now.ToString("dd/MM/yyyy");
            b = label32.Text;
            OleDbConnection con = new OleDbConnection();

            con.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Rock.accdb";
            con.Open();
            var query1 = "SELECT datear FROM leave WHERE name='" + label14.Text + "'";
            using (var command = new OleDbCommand(query1, con))
            {
                using (var reader = command.ExecuteReader())
                {

                    while (reader.Read())
                    {
//this is where i get error 
                        a = reader.GetString(reader.GetOrdinal("datear")).ToString();
                        DateTime d = Convert.ToDateTime(a);
                        DateTime f = Convert.ToDateTime(b);
                        d.ToString("dd/MM/yyyy");
                        f.ToString();
                        if (d > f)
                        {
                            label30.Text = "On Campus";
                        }
                        else
                        {
                            label30.Text = "Off Campus";
                        }

                    }
                }
            } con.Close();

2 个答案:

答案 0 :(得分:1)

替换此a = reader.GetString(reader.GetOrdinal("datear")).ToString();

到这个

a= reader.GetDateTime(0).ToString();

感谢大家花时间解决我的问题...

答案 1 :(得分:0)

尝试使用DateTime.Parse()方法:

替换此部分:

DateTime d = Convert.ToDateTime(a);
DateTime f = Convert.ToDateTime(b);
d.ToString("dd/MM/yyyy"); // it just a call of a method, it doesn't change the state of the object
f.ToString(); // it too

要:

DateTime d = DateTime.Parse(a);
DateTime f = DateTime.Parse(b);
if (d > f)
{
    label30.Text = "On Campus";
}
// and so on