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

I am using Visual Studio 2010 and SQL Management Studio R2. Although the sql query works fine in sql management studio. This makes an exception in visual studio. From the exclusion of the index, which I am editing to make any other adjustments that it throws out of the format exception. Please, help. 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()); } } 
+6
source share
3 answers

You do not select tdate , but you select Year(tdate)

I would change the request to this:

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

and access it using dr["tdate_year"]

+4
source

You missed to specify a column name in sql query

try it

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

It looks like you did not tdate alias for your tdate request. Therefore, when trying to reference tdate column does not exist, and Visual Studio throws an error.

Change the request to:

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

which will return all your results under the tdate column tdate .

+2
source

Source: https://habr.com/ru/post/944106/


All Articles