如何在c#中从日期时间列中选择不同的年份并将结果添加到组合框中
本文关键字:结果 添加 组合 日期 时间 选择 | 更新日期: 2023-09-27 18:11:51
我使用visual studio 2010和SQL Management studio R2虽然sql查询在sql管理工作室工作得很好。它在visual 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"]
您在sql查询
中错过了提供列名试试这个
string sql = "SELECT DISTINCT Year(tdate) AS tdate FROM saletransaction ORDER BY Year(tdate) DESC";
看起来您没有给您的tdate
查询别名。因此,当您尝试引用tdate
时,列不存在并且Visual Studio抛出错误。
将查询改为:
string sql = "SELECT DISTINCT Year(tdate) AS tdate FROM saletransaction ORDER BY Year(tdate) DESC";
返回列名称tdate
下的所有结果。