Tuesday, February 9, 2010

.NET Windows Form - Display the standard DataLink property dialog box as child window of current form

Want to shared some of my experience to use DataLink form to edit database connection string in windows form application.

The hardest part is to set DataLink form as child window of current form. But fortunately, I find a way to set HWnd property to get it solved.

Here is the code:

  1: Public Function GetConnection() As String
  2:     Dim dc As MSDASC.DataLinks = New MSDASC.DataLinksClass()
  3:     Dim oConnection As Object = GetFakeOledbConnectionString(existingConnectionString)
  4:     dc.hWnd = Me.Handle    '//Set parent window to current form    
  5:     If dc.PromptEdit(oConnection) Then
  6:        Return CType(oConnection, ADODB._Connection).ConnectionString
  7:     Else
  8:        Return Nothing
  9:     End If
 10: End Function
 11: 
 12: Private Function GetFakeOledbConnectionString(ByVal str As String) As Object
 13:     If String.IsNullOrEmpty(str) Then
 14:         str = "Integrated Security=SSPI; Persist Security Info=True;Password=1;"
 15:     End If
 16:     If Not str.StartsWith("Provider", StringComparison.OrdinalIgnoreCase) Then
 17:         str = "Provider=SQLOLEDB;" + str
 18:         str = str.Replace("Integrated Security=True", "Integrated Security=SSPI")
 19:         If Not str.ToLower().Contains("Persist Security Info".ToLower()) Then
 20:             str = str.TrimEnd(" ").TrimEnd(";") + "; Persist Security Info=True;"
 21:         End If
 22:     End If
 23:     Dim position As Integer = str.IndexOf("AttachDBFile", StringComparison.OrdinalIgnoreCase)
 24:     If position > 0 Then
 25:         str.Replace("AttachDbFilename=;", "")
 26:     End If
 27:     Dim adoConnection As ADODB._Connection = New ADODB.ConnectionClass()
 28:     adoConnection.ConnectionString = str    
 29:     Return adoConnectionEnd 
 30: Function

No comments: