Saturday, March 03, 2007

ListBox tricky to set in a DataGrid/GridView

Listboxes are very tricky to set selected items in grid - there is no real nice way to do it. It would have been great if Microsoft included a property that accepts an array or comma separated values - or anything! But they only allow each item in the list to be selected individually. The way to do this in a grid is a bit messy, but it is fairly simple to implement. When a row is created (as per the event), select the items of the listbox as per the datagrid source data:

HTML code:
<asp:listbox id="listBox" DataSource="<%# dtCase_Type %>" runat="server" selectionmode="Multiple" datasource="" datavaluefield="Code" datatextfield="Description">

VB code behind:
Private Sub myDataGrid_Itembound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles myDataGrid.ItemDataBound
If e.Item.ItemType = ListItemType.EditItem Then
Dim intRow As Integer = CInt(e.Item.ItemIndex)
If Not IsDBNull(datatableCache.Rows(intRow)("DataFieldFromDataStore")) Then
'datatableCache.Rows(intRow)("DataFieldFromDataStore") contains the list of values (in this case comma seperated)
Dim aryValues() As String = datatableCache.Rows(intRow)("DataFieldFromDataStore").ToString.Split(","c)
Dim listBox As ListBox = e.Item.FindControl("listBox")
For Each li As ListItem In listBox.Items
If Array.IndexOf(aryValues, li.Value) > -1 Then li.Selected = True
Next
End If
End If
End Sub

CDO for receiving emails via SMTP

I recently discovered that .NET 2.0 does not have an inbuilt class for receiving emails via SMTP (or by any other means). Surprising omission. I started to write my own email file parser, but then had a thought... Why not use the old CDO (aka CDOSYS) like the old ClassicASP days? This is how to do it...

Create a reference in Visual Studio to Microsoft CDO for Windows 2000. Now use some code like this:

Dim objSMTP As New System.Net.Mail.SmtpClient
Dim strMailbox As String = objSMTP.PickupDirectoryLocation.Substring(0, objSMTP.PickupDirectoryLocation.LastIndexOf("\")) & "\Mailbox"
Dim CDODropDir As New CDO.DropDirectory
Dim CDOMessages As CDO.IMessages = CDODropDir.GetMessages(strMailbox)
Dim CDOMessage As CDO.Message
For Each CDOMessage In CDOMessages
'Some useful properties:
'CDOMessage.To, CDOMessage.CC, CDOMessage.BCC, CDOMessage.From
'CDOMessage.ReceivedTime, CDOMessage.Subject
'CDOMessage.TextBody, CDOMessage.HTMLBody
'CDOMessages.FileName(CDOMessage) '--Useful for deleting messages later (after you read the whole collection first!)
Next