Reputation: 7532
I have a drop down menu that is populated from a database:
<asp:DropDownList ID="searchApplicationDropDown" runat="server"
DataSourceID="SqlDataSource8" DataTextField="AppName"
DataValueField="PK_Application"></asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource8" runat="server"
ConnectionString="<%$ ConnectionStrings:ApplicationServices %>"
SelectCommand="SELECT [PK_Application], [AppName] FROM [Application]">
</asp:SqlDataSource>
How do I add a row at the top manually outside of the database?
Upvotes: 2
Views: 634
Reputation: 1375
Use PreRender
protected void Page_PreRender(object sender, EventArgs e)
{
searchApplicationDropDown.Items.Insert(0 , new ListItem("Select...", ""));
}
Upvotes: 1
Reputation: 653
Use the AppendDataBoundItems
property of DropDownList
like so:
<asp:DropDownList
ID="searchApplicationDropDown" runat="server"
AppendDataBoundItems="true"
DataSourceID="SqlDataSource8"
DataTextField="AppName"
DataValueField="PK_Application">
<asp:ListItem Text="--Select One--" />
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource8" runat="server"
ConnectionString="<%$ ConnectionStrings:ApplicationServices %>"
SelectCommand="SELECT [PK_Application], [AppName] FROM [Application]">
</asp:SqlDataSource>
Upvotes: 2
Reputation: 714
Try this:
searchApplicationDropDown.Insert(0, new ListItem() { Text = "", Value = "value" });
Upvotes: 0
Reputation: 67898
Since you're just trying to get a default row at the top. One approach would be this:
<asp:SqlDataSource ID="SqlDataSource8" runat="server"
ConnectionString="<%$ ConnectionStrings:ApplicationServices %>"
SelectCommand="SELECT -1 AS [PK_Application], 'Please select an application...' AS [AppName] UNION ALL SELECT [PK_Application], [AppName] FROM [Application]">
</asp:SqlDataSource>
I'm not sure that [PK_Application]
is an int
, but you could modify the SELECT
as necessary to get it to sort. You may even need to modify the Please select an application...
to be something like (Please select an application...)
to get it sort right.
Upvotes: 1
Reputation: 34846
You need to handle the DataBound
event of the dropdown list (which occurs after all of the values from the database have been put into the dropdown list), like this:
Markup:
<asp:DropDownList ID="searchApplicationDropDown" runat="server"
DataSourceID="SqlDataSource8" DataTextField="AppName"
DataValueField="PK_Application" OnDataBound="searchApplicationDropDown_DataBound"></asp:DropDownList>
Code-behind:
protected void searchApplicationDropDown_DataBound(object sender, EventArgs e)
{
DropDownList list = sender as DropDownList;
if (list != null)
{
list.Items.Insert(0, "--Select One--");
}
}
Upvotes: 2