The code here creates a dropdown menu of abbreviations for different location. What I'm trying to do is to get all the abbreviation in alphabetical order. How do I go about doing that?
<asp:DropDownList ID="ddl_loc" runat="server" DataSourceID="CriticalLog"
DataTextField="abbrev" DataValueField="recordKey" Height="16px"
style="margin-bottom: 8px"
ToolTip="Select your Location for updating." AutoPostBack="True"
onselectedindexchanged="ddl_loc_SelectedIndexChanged"
AppendDataBoundItems="True" CssClass="auto-style9" Width="184px">
<asp:ListItem Value="-1">"-- Choose a Location --"
</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="CriticalLog" runat="server"
ConnectionString="<%$ ConnectionStrings:CriticalLogConnectionString %>"
SelectCommand="SELECT DISTINCT [name], [recordKey],[abbrev], [phone2], [phone1] , [type] FROM [location] where [name] NOT LIKE '(%' ORDER BY [type],[abbrev]">
</asp:SqlDataSource>
<div >
<asp:Label ID="lbl_Loc" runat="server" Font-Bold="True" Font-Size="Large"
Font-Underline="True" ToolTip="Location"></asp:Label>
</div>
CodePudding user response:
Well, you useally need (have) some data source for the drop down.
So, say this drop down:
<h3>Select Hotel</h3>
<asp:DropDownList ID="cboHotel2" runat="server"
DataValueField="ID"
DataTextField="HotelName"
Width="288px">
</asp:DropDownList>
Now, to fill above, we go:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadCombo2();
}
void LoadCombo2()
{
string strSQL = "SELECT ID, HotelName FROM tblHotels ORDER BY HotelName";
DataTable rst = MyRst(strSQL);
cboHotel2.DataSource = rst;
cboHotel2.DataBind();
cboHotel2.Items.Insert(0, new ListItem("Please Select", "0"));
}
And now we see this:
So, really, the "common" way to approach this problem, is we order/sort and setup the data BEFORE we sent it to the drop down list.
And I did use that helper routine MyRst, since that just saves a lot of re-typing of code. that helper routine (I usually put in a global set of routines - used it for years). Is this:
public DataTable MyRst(string strSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
So, be it some list, some table, or whatever data you have to drive the combo box? Sort the data before you SEND the data to the drop down.
Lists, even tables (default view) all have the ability to sort - even if the original source data was not sorted.
CodePudding user response:
Just change your SelectCommand's order by
:
SelectCommand="SELECT DISTINCT [name], [recordKey],[abbrev], [phone2], [phone1] , [type] FROM [location] where [name] NOT LIKE '(%' ORDER BY [abbrev]"