2013-05-02 33 views
6

我正在使用visual studio 2010和SQL Management Studio R2 虽然sql查询在sql管理工作室中工作正常。它在视觉工作室中引发异常。超出索引异常我编辑进行任何其他调整时抛出格式异常。请帮帮我。代码如下:如何从日期时间列中选择不同年份并将结果添加到C#中的组合框?

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()); 
    } 
} 
+0

数据库中日期时间的格式是什么? – 2013-05-02 08:38:12

+0

tdate已经转换为简单的年份,即简单的字符串,所以错误可能是因为您正在尝试一个简单的年份字符串datetime。 – Paras 2013-05-02 08:39:57

回答

4

你不选择tdate但你选择Year(tdate)

我会修改查询到这一点:

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

和访问它与dr["tdate_year"]

+0

我明白了。谢谢Wouter Huysentruit。 – 2013-05-02 08:50:47

3

您错过了在sql查询中提供的列名称

试试这个

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

非常感谢Mandeep Singh。你很容易解决它! – 2013-05-02 08:47:19

+0

你总是欢迎 – 2013-05-02 10:32:04

2

看起来你没有给一个别名到您的tdate查询。因此,当您尝试引用tdate时,该列不存在,Visual Studio将引发该错误。

查询更改为:

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

将返回列名tdate下的所有搜索结果。

+0

我明白了。谢谢Darren Davies。 – 2013-05-02 08:50:21

+0

@Suvee-你能否请你停止标记答案被接受,然后不被接受。它在最后一天改变了3次。 – 2013-05-03 13:11:24

+0

对不起。我不知道我只能接受一个答案。 – 2013-05-03 13:55:40

相关问题