Lining up columns in an Asp.net Combobox / Listbox.
I have been long searching for a solution to formatting columns in a combobox or listbox. There are some third party controls out there that provide columns in a listbox or combobox, but I was looking for something simple, and free.
I finally came apon this workaround to line up columns in a listbox or combobox. The only thing is to make sure your box is using a Monospaced font like Courier New.
Essentially it is taking the string and padding it out so many spaces:
Dim dr As DataRow
For Each dr In DT.Rows
Dim LI As New ListItem(dr("file_name").ToString.PadRight(45, Chr(160)) & dr("last_modified").ToString, dr("id").ToString)
Me.ListBox1.Items.Add(LI)
Next
This will give the ListItem a Text value of the file_name field padded to a total of 45 characters with a non-breaking space ( ) and concatenate the last_modified field right after. It will give the ListItem a Value of the ID for the record.
Retrieving Data from the Listbox.
First, make sure your listbox has the AutoPostBack property set to True. This will trigger a postback when the user clicks on your listbox.
Next, in the SelectedIndexChanged Subroutine, put the following code:
Protected Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
Dim sId As String = sender.selectedvalue
Dim sSelected As String = sender.selecteditem.text
Dim Song As String = sSelected.Substring(0, 44).Trim
Dim Last_modified As String = sSelected.Substring(45, sSelected.Length - 45).Trim
End Sub
This code grabs the ID from the sender's selected value property. This was set in the code above. To get the individual column's value, we will substring the value. This is made easier because we know how much we are padding the fields, and will simply trim off the excess spaces using the trim command.
Notice on the Last_modified the substring has a length of sSelected.Length - 45. This ensures that the Substring method will not try to look for a value that is longer than the actual value, which would throw an error. Use this on the last column in your listbox.
Thats it. Use this next time you are looking to make neat columns in your Asp.net Listboxes!