I have a dropdownlist, which dynamically populate data from SQL Server and i wanna manually insert two items on top of the DDL after data binding. So, the DDL would has data something like this:
Select Branch (manually insert)
ALL (manually insert) AIR AMP ABG ...I tried to achieve it by using code below:
ddlBranch.Items.Insert(0, "Select Branch")
ddlBranch.Items(0).Value = CMM.sExcVal1
ddlBranch.Items.Insert(1, "ALL")
ddlBranch.Items(1).Value = "ALL"
but it comes out giving me the data like this:
Select Branch (manually insert)
ALL (manually insert) ('AIR' branch should be here but it's gone) AMP ABG 开发者_开发技巧 ...After manually insert the 'ALL' item into the DDL, the 'AIR' is gone which is already replaced by the 'ALL'. How can i remain all the data from server and at the same time i can manually insert two items?
It is much simpler than you think. All you need to do is change the html code as below:
<asp:DropDownList ID="dropdownlist1" runat="server" AppendDataBoundItems="true">
<asp:ListItem>Select Branch</asp:ListItem>
<asp:ListItem>ALL</asp:ListItem>
</asp:DropDownList>
The important thing is the AppendDataBoundItems="true" bit, which will append the remaining items that will be brought back from the SQL Server as normal (however you did it) after the two entries you manually typed in.
Hope that helps.
Ash (UK).
Just skip the automatic databinding.
if (!IsPostBack)
{
list.Items.Clear();
list.Items.Add(new ListItem("Select branch", ""));
list.Items.Add(new ListItem("ALL", "*");
// ----- Just bind your items here from the DB.
foreach (var item in yourCollection)
{
ListItem li = new ListItem(item.Text, item.Value);
list.Items.Add(li);
}
}
Alternatively, if you need this placeholder item in a lot of places in your app - you might want to create a Component that inherits from DropDownList. Then, override the DataBind method -
public override void DataBind()
{
base.DataBind();
ListItem li = new ListItem { Value = String.Empty, Text = "[Select an item ...]" };
this.Items.Insert(0, li);
}
精彩评论