a2wd | code & design

Single post

Howto: Make changes to DropDownList items values & display text.

    Visual Basic (VB.net) & ASP.net

For a recent project I am dynamically binding a DropdDownList to a datasource (in this instance, a DataTable returned from SQL Server).

The user needed to see a series of formatted strings (the index column) in the DropDownList but I couldn’t find anything on how to do this. The index returned from the SQL database held the item number and I needed to transform that into “No.:xxxxxx” with five digits of zero-padding.

My first approach was to modify the DataTable prior to DataBinding by adding a column with an expression:

DataTable.Columns.Add("FormattedIndex", Type.GetType("System.String"), "'No.:'+Index")

(The third parameter is the expression).

But the DataTable Expression property doesn’t have any functions for handling number-formatting.

The alternative and working solution was to modify the DropDownList via the DataBound method:

Private Sub DropDownList_DataBound(sender As Object, e As EventArgs) Handles DropDownList.DataBound
 'Rewrite text of items to include "No.:" prefix and 5-digit zero-padding
 For Each Item As ListItem In sender.Items
 Item.Text = String.Format("No.:{0:D5}", Integer.Parse(Item.Text))
End Sub

And iterate through the ListItems being bound. One thing to note, many developers prefer to insert an item at index 0 with “Please Select” (as per):

DropDownList.Items.Insert(0, New ListItem("Please Select", ""))

This works fine with the above if DropDownList.DataBind() is called before the Insert()

22 Jan 2015.net / ASP / VB

  • Recent Posts

  • Archives