C# 如何从datetime列中选择不同的年份,并将结果添加到C中的组合框中?

C# 如何从datetime列中选择不同的年份,并将结果添加到C中的组合框中?,c#,sql,.net,sql-server,visual-studio-2010,C#,Sql,.net,Sql Server,Visual Studio 2010,我正在使用visual studio 2010和SQL Management studio R2 尽管sql查询在sql management studio中运行良好。它在VisualStudio中引发了一个异常。索引外异常当我编辑以进行任何其他调整时,它会抛出格式外异常。请帮帮我。代码如下: string sql = "SELECT DISTINCT Year(tdate) FROM saletransaction ORDER BY Year(tdate) DESC"; cmd = new

我正在使用visual studio 2010和SQL Management studio R2 尽管sql查询在sql management studio中运行良好。它在VisualStudio中引发了一个异常。索引外异常当我编辑以进行任何其他调整时,它会抛出格式外异常。请帮帮我。代码如下:

 string sql = "SELECT DISTINCT Year(tdate) FROM saletransaction ORDER BY Year(tdate) DESC";
 cmd = new SqlCommand(sql, con);                
 dr = cmd.ExecuteReader();
 DateTime dt;
 while (dr.Read())
 {
     if (dr.HasRows == true)
     {
         dt = Convert.ToDateTime(dr["tdate"].ToString()); //tdate is the name of the column (getting an error at this line. )
         comboBox1.Items.Add(dt.Year.ToString());
     }
 }
您选择的不是日期,而是年份日期

我会将查询修改为:

string sql = "SELECT DISTINCT Year(tdate) AS tdate_year FROM saletransaction ORDER BY Year(tdate) DESC";

并使用dr[tdate_year]访问它。

您在sql查询中没有提供列名

试试这个

string sql = "SELECT DISTINCT Year(tdate) AS tdate FROM saletransaction ORDER BY Year(tdate) DESC";

看起来您没有为tdate查询提供别名。因此,当您尝试引用tdate时,该列不存在,VisualStudio将抛出错误

将查询更改为:

 string sql = "SELECT DISTINCT Year(tdate) AS tdate FROM saletransaction ORDER BY Year(tdate) DESC";

它将返回列名称tdate下的所有结果

数据库中日期时间的格式是什么?tdate已转换为简单年份,即简单字符串,因此错误可能是因为您试图将简单年份字符串转换为datetime。我知道了。谢谢Darren Davies。@Suvee-你能不能别再把答案分为“已接受”和“未接受”。在过去的一天里已经换了三次了,我明白了。谢谢你惠斯特·休斯中心。