Skip to content
Advertisement

How to select distinct year from a datetime column and add the result to a comboBox in C#?

I am using visual studio 2010 and SQL Management Studio R2 Although the sql query works fine in sql management studio. Its throws an exception in visual studio. Out of index exception whem i edit to make any other adjustments it throws Out of format exception. Please Help me. The code is as follows:

 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());
     }
 }

Advertisement

Answer

You’re not selecting tdate but you select Year(tdate)

I would modify the query to this:

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

and access it with dr["tdate_year"]

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement