user3340627
user3340627

Reputation: 3143

Add an item to a drop down list which is bound dynamically

I'm binding my Drop Down List to a DataSource Dynamically as follows:

DDLRecordStatus.DataSource = BLREOptions.getRecordStatusList();
DDLRecordStatus.DataTextField = "OptionName";
DDLRecordStatus.DataValueField = "OptionValue";
DDLRecordStatus.DataBind();

However, the datasource does not contain a null or empty option, I need to add an item Name " "(Blank) and with value -1 to the Drop Down List that appears as the first choice, is this possible ?

Upvotes: 0

Views: 5390

Answers (2)

Andrei
Andrei

Reputation: 56726

Of course this is possible, you just need to insert it manually after data binding is done:

DDLRecordStatus.DataBind();
DDLRecordStatus.Items.Insert(0, new ListItem(" ", "-1"));

Alternatively you can specify it directly in the markup:

<asp:DropDownList ID="DDLRecordStatus"
     ...
     AppendDataBoundItems="True">
    <asp:ListItem Text=" " Value="-1" />
</asp:DropDownList>

Notice AppendDataBoundItems property, which makes sure default list item is not erased.

Upvotes: 3

Grant Winney
Grant Winney

Reputation: 66511

Insert the record into the list before binding to the control. I'll just assume the class is called Status:

var statusList = BLREOptions.getRecordStatusList();
statusList.Insert(0, new Status { OptionName = "", OptionValue = -1 });

DDLRecordStatus.DataSource = statusList;

Upvotes: 1

Related Questions