我正在使用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());
}
}
数据库中日期时间的格式是什么? – 2013-05-02 08:38:12
tdate已经转换为简单的年份,即简单的字符串,所以错误可能是因为您正在尝试一个简单的年份字符串datetime。 – Paras 2013-05-02 08:39:57