我正在尝试按价格对我的数据(在数据列表中)进行排序。这意味着有 DropDownList 供用户选择,如果他们想要从最贵到最便宜的价格,反之亦然。存储在我的数据库中的价格是根据我的 catID 随机排列的。我已经编写了如下代码,但它没有按照我写的内容进行排序。我在这里做错了什么?请给我建议。
protected void Page_Load(object sender, EventArgs e)
{
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
bindDropDownList();
}
private void bindDropDownList()
{
DropDownList1.DataTextField = "price";
DataList1.DataSourceID = null;
DataList1.DataSource = getReader();
DropDownList1.DataBind();
}
private SqlDataReader getReader()
{
SqlDataReader reader = null;
if(DropDownList1.Text == "-Select-")
{
string strConnectionString =
ConfigurationManager.ConnectionStrings["ProBizConnection"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText ="SELECT * FROM [Category ] WHERE catID<= 20";
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
myConnect.Open();
reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
else if (DropDownList1.SelectedValue == "Price - Highest to Lowest")
{
string strConnectionString =
ConfigurationManager.ConnectionStrings["ProBizConnection"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "SELECT catID, packageName, price, description1, description2, image1, image2 FROM Category WHERE catID <= 20 ORDER BY price desc";
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
myConnect.Open();
reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
else if (DropDownList1.DataTextField == "Price - Lowest to Highest")
{
/string strConnectionString =
ConfigurationManager.ConnectionStrings["ProBizConnection"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "SELECT catID, packageName, price, description1, description2, image1, image2 FROM Category WHERE catID <= 20 ORDER BY price";
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
myConnect.Open();
reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
return reader;
}
我的 .aspx 代码:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" AppendDataBoundItems="true"
onselectedindexchanged="DropDownList1_SelectedIndexChanged" Height="18px"
Width="184px">
<asp:ListItem>-Select-</asp:ListItem>
<asp:ListItem>Price - Highest to Lowest</asp:ListItem>
<asp:ListItem>Price - Lowest to Highest</asp:ListItem>
</asp:DropDownList>