微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我正在使用visual studio 2010和sql Management Studio R2
虽然SQL查询sql management studio中工作正常.它在视觉工作室中引发了一个例外.超出索引例外,当我编辑进行任何其他调整时,它会抛出格式异常.请帮我.代码如下:
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());
     }
 }

解决方法

你没有选择tdate但是你选择了Year(tdate)

我会将查询修改为:

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

并使用dr [“tdate_year”]访问它

原文地址:https://www.jb51.cc/csharp/91552.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐