C# · 12月 23, 2021

如何从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. ) combo@R_671_2419@1.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”]访问它