Search code examples
c#sqlasp.netdropdownbox

Dropdownbox.selectedvalue passing to sql comment


string ddorder = DropDownList2.SelectedValue; // column
string ddtype = DropDownList3.SelectedValue; //asc or desc
String str1 = "Select * from table1 order by("+ddorder+"  "+ddtype+")";

//there is an error beacuse of ddtype, what am I doing wrong?

SqlCommand cmd = new SqlCommand(str1, con);
con.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter da1 = new SqlDataAdapter();
da1.SelectCommand = cmd;
DataSet ds1 = new DataSet();
da1.Fill(ds1, DropDownList2.SelectedValue);
GridView2.DataSource = ds1;
GridView2.DataBind();
con.Close();

Solution

  • As far as I can see, you don't need to use ( and ) in order by clause. It's syntax doesn't have any usage for ( or ).

    For example;

    order by id desc
    

    will work but

    order by (id desc)
    

    won't work.

    By the way, use using statement to dispose your SqlConnection, SqlCommand and SqlDataAdapter automatically instead of calling Close method manually.

    Also you don't need cmd.ExecuteNonQuery(); part for a SELECT statement. It is unnecessary since it's just execute your select query. It doesn't do or return something.

    A few things more;

    • Change your table1 to something meaningful.
    • Don't use SELECT *. It's quite bad.