Populating a drop down list dynamically in ASP.net, and passing that value to another query?

dev6546 picture dev6546 · May 8, 2012 · Viewed 11.9k times · Source

2 questions for everybody.

1) How can I order the years by their value, it crashes when I use DESC?

2) If I populate my list like so:

 string strConn = ConfigurationManager.ConnectionStrings["rde_410978ConnectionString"].ToString();
    SqlConnection con = new SqlConnection(strConn);
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = con;
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "Select Distinct Year from MonthlySales DESC"; //DESC DOESNT WORK?

    DataSet objDs = new DataSet();
    SqlDataAdapter dAdapter = new SqlDataAdapter();
    dAdapter.SelectCommand = cmd;
    con.Open();
    dAdapter.Fill(objDs);
    con.Close();

    if (objDs.Tables[0].Rows.Count > 0)
    {
        ddItems.DataSource = objDs.Tables[0];
        ddItems.DataTextField = "Year";
        ddItems.DataValueField = "Year";
        ddItems.DataBind();
        ddItems.Items.Insert(0, "Select");
    }

How can I make the year selected appear under ddItems.SelectedItem?

WHERE Year = " + ddItems.SelectedItem + "GROUP BY Name ";

That part of another query doesn't work when I populate my list dynamically, any reasons why/ how can I fix it.

Regards.

EDIT: To make my second question clearer, after debugging its always selecting the top item in the drop down list not the actual selected item?

Answer

Adil picture Adil · May 8, 2012

Ans 1)

cmd.CommandText = "Select Distinct Year from MonthlySales ORDER BY 1 DESC"