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

前端之家收集整理的这篇文章主要介绍了如何从datetime列中选择不同的年份并将结果添加到C#中的comboBox?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用visual studio 2010和sql Management Studio R2
虽然SQL查询sql management studio中工作正常.它在视觉工作室中引发了一个例外.超出索引例外,当我编辑进行任何其他调整时,它会抛出格式异常.请帮我.代码如下:
  1. string sql = "SELECT DISTINCT Year(tdate) FROM saletransaction ORDER BY Year(tdate) DESC";
  2. cmd = new sqlCommand(sql,con);
  3. dr = cmd.ExecuteReader();
  4. DateTime dt;
  5. while (dr.Read())
  6. {
  7. if (dr.HasRows == true)
  8. {
  9. dt = Convert.ToDateTime(dr["tdate"].ToString()); //tdate is the name of the column (getting an error at this line. )
  10. comboBox1.Items.Add(dt.Year.ToString());
  11. }
  12. }

解决方法

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

我会将查询修改为:

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

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

猜你在找的C#相关文章