我很好奇在 C#/ASP.NET 中对 DropDownList 进行排序的最佳路线(更注重简单性,而不是速度或效率) - 我已经查看了一些建议,但它们并不适合我。这个下拉菜单按字母顺序给我列表。但我必须随机整理。
注意:我无法控制数据如何进入 DropDownList - 我无法修改 SQL。
public void populateLocationList()
{
DataTable dt_locations = (DataTable)daa_addresses.GetDataByEventLocations(int_eventid);
if (dt_locations != null && dt_locations.Rows.Count > 0)
{
// Populate locations dropdown menu
// Bind locationsList instead of dt_locations
ddl_locations.DataTextField = "Key";
ddl_locations.DataValueField = "Value";
ddl_locations.DataSource = RemoveDuplicateLocations(dt_locations);
ddl_locations.DataBind();
string location = "";
// Set the selection based upon the query string
if (Request.QueryString["loc"] != null)
{
location = Request.QueryString["loc"];
locationLbl.Text = Request.QueryString["loc"];
locationID.Value = "-1";
}
if (dt_locations.Rows.Count == 1)
{
location = ddl_locations.Items[0].Text;
locationLbl.Text = location;
}
// Set location in drop down list
int int_foundlocation = 0;
bool foundLocation = false;
foreach (ListItem lsi_item in ddl_locations.Items)
{
if (lsi_item.Text.ToLower().Trim() == location.ToLower().Trim())
{
int_foundlocation = ddl_locations.Items.IndexOf(lsi_item);
foundLocation = true;
break;
}
}
ddl_locations.SelectedIndex = int_foundlocation;
if (ddl_locations.Items.Count == 1)
{
// Make location label visible.
locationLbl.Visible = true;
ddl_locations.Visible = false;
}
else
{
locationLbl.Visible = false;
ddl_locations.Visible = true;
}
//* defualt location S for short courses *//
if (!IsPostBack && !foundLocation)
{
ListItem s = ddl_locations.Items.FindByText("S");
int index = 0;
if (s != null)
{
index = ddl_locations.Items.IndexOf(s);
}
ddl_locations.SelectedIndex = index;
ddl_locations.DataBind();
}
}
}