Using VB .Net WebBrowser Control To Build WinForm User Interface

Most application use textbox, frame, picturebox, label, listbox, combobox controls etc to make a user interface.
On the other hand WebBrowser Control commonly used to browse online website. However WebBrowser Control can be used to build rich user interface. We can develop any project i.e database, files, streaming operation.
The requirements are only knowledge of html tags, methods and behaviour of WebBrowser Control itself. In my opinion, it is easier to develop using webbrowser’s html rather than label, textbox, picturebox controls etc

Key points to develop with webbrowser on VB .Net 2010 are:

  1. WebBrowser1_Navigating and additionally WebBrowser1_DocumentCompleted methods
  2. WebBrowserNavigatingEventArgs and additionally WebBrowserDocumentCompletedEventArgs
  3. Url property
  4. DocumentText property
  5. HtmlElement class, GetElementById and GetAttribute functions to retrieve html element value.

Here’s example of managing person names stored on System.Collections.Generic.SortedDictionary Class or just SortedDictionary (Represents a collection of key/value pair that or sorted on the key) :

  1. Create Visual Basic new Window Application Project. Drag & drop WebBrowser Control on Form. You can rename the form to frmmain. WebBrowser has name WebBrowser1.
    Add WebBrowser Control Into Form
  2. Switch to code view and write to declare arrName (Person name container):
    Public Class frmmain
        Dim arrName As SortedDictionary(Of Integer, String)
    End Class
    
  3. Create procedure frmmain_load that handles form load event. Just click on visual studio control drop down choose ‘frmmain events’ and choose ‘Load’ on its right side drop down.

    Code will automatically generated.

    Private Sub frmmain_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            arrName = New SortedDictionary(Of Integer, String)
    End Sub
    

    Initialize arrName with key as Integer and value as string.

  4. Create procedure to build user interface on webbrowser:
    Private Sub MainPage()
            Dim strhtml As String
            strhtml = "<html><body><h3>List Names</h3>"
            strhtml = strhtml & "<input type=text id='txname'> &nbsp;<input type=button id='btnadd' value='Add' onclick=""location.href='schname://add'""><br>"
            For Each id As Integer In arrName.Keys
                strhtml = strhtml & id & " " & arrName(id) & " <a href='schname://delete?id=" & id & "'>Delete</a><br>"
            Next
            strhtml = strhtml & "</body></html>"
            WebBrowser1.DocumentText = strhtml
        End Sub
    

    WebBrowser1 has property DocumentText and we set it to string contains complete html page. So Webbrowser1 has html source.

  5. Edit frmmain_Load procedure to:
    Private Sub frmmain_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            arrName = New SortedDictionary(Of Integer, String)
            MainPage()
        End Sub
    

    Run the project and it appears:

  6. Create procedure to handle add person name.
    Private Sub AddName()
            Dim txelem As HtmlElement
            txelem = WebBrowser1.Document.GetElementById("txname")
            Dim strname As String = ""
            If (IsDBNull(txelem) = False) Then
                strname = txelem.GetAttribute("value")
            End If
            Dim lastname As KeyValuePair(Of Integer, String)
            Dim nextid As Integer
            If arrName.Count &gt; 0 Then
                lastname = arrName.Last()
                nextid = lastname.Key + 1
            Else
                nextid = 1
            End If
            arrName.Add(nextid, strname)
    
        End Sub
    

    Use WebBrowser1.Document.GetElementById(“txname”) to get input box element with id “txname”. Get input value with GetAttribute(“value”) function attached to html element.
    Actually we can use WebBrowser1.Document.GetElementById(“txname”).GetAttribut(“value”) to get the input value. I just want to give you more granular way so that you can do more using HTMLElement Object.
    We use incremental integer id on SortedDictionary collection as a key. To get last element on name collection we use Last() method and assign it to keyValuePair variable. Last id is just key to that variable.
    Next id would be last id plus one. If no name added then next id is one.
    Use arrName.Add(key, value) method with parameter nextid and strname to add id and name to collection.

  7. Create procedure to handle delete person name.
    Private Sub DeleteName(ByVal id As Integer)
            arrName.Remove(id)
        End Sub
    
  8. Create procedure WebBrowser1_Navigating as a trigger to execute AddName() and DeleteName().
    Private Sub WebBrowser1_Navigating(ByVal sender As Object, ByVal e As System.Windows.Forms.WebBrowserNavigatingEventArgs) Handles WebBrowser1.Navigating
            Dim _get As Dictionary(Of String, String)
            Select Case e.Url.Scheme
                Case "schname"
                    e.Cancel = True
                    Select Case e.Url.Host
                        Case "add"
                            AddName()
    
                    End Select
                    MainPage()
            End Select
        End Sub
    

    To get Url path we can use e.Url.ToString(). Url object has some properties like Scheme, host, query. e.Url.Scheme is a scheme name of this URL. It is pretty much same as protocol which are http, ftp.
    Host is a Url host. It is web address we browse. Query is a querystring of url address. This page has html button . “schname” is Scheme of Url, “add” is host. You can set whatever string you like. If this button clicked then web browser will navigate to address schname://add.
    We catch the Navigating process with above procedure. When e.Url.Scheme is “schname” then navigation is canceled with e.Cancel = True because this url path is not valid online address.
    After navigation canceled we do another check to host property. If e.Url.Host is “add” then AddName() is executed.
    Now, run this project again.

  9. Delete link also appear in page because of Delete in MainPage procedure. We see that url has querystring to set id variable to related id.
    Querystring is key value pair with separator “&” and “=”. “&” is used for multiple variables. So we need to create function that extracts querystring to collection Dictionary Class.
    We use Dictionary Class instead of SortedDictionary Class because of we don’t need to sort querystring keys.

    Private Function extract_querystring(ByVal strquery As String) As Dictionary(Of String, String)
            Dim strtemp As String = Replace(strquery, "?", "")
            Dim arrkeyval As String()
            Dim arrdict As New Dictionary(Of String, String)
            arrkeyval = strtemp.Split("&")
            For Each strkeyval As String In arrkeyval
    
                Dim pos As Integer
                Dim key, value As String
                pos = InStr(1, strkeyval, "=", Microsoft.VisualBasic.CompareMethod.Text)
                key = strkeyval.Substring(0, pos - 1)
                value = strkeyval.Substring(pos)
    
                arrdict.Add(key, value)
            Next
            Return arrdict
        End Function
    
  10. Edit WebBrowser1_Navigating procedure to:
    Private Sub WebBrowser1_Navigating(ByVal sender As Object, ByVal e As System.Windows.Forms.WebBrowserNavigatingEventArgs) Handles WebBrowser1.Navigating
    
            Dim _get As Dictionary(Of String, String)
            Select Case e.Url.Scheme
                Case "schname"
                    e.Cancel = True
                    Select Case e.Url.Host
                        Case "add"
                            AddName()
                        Case "delete"
                            _get = extract_querystring(e.Url.Query)
                            DeleteName(_get("id"))
                    End Select
                    MainPage()
            End Select
    End Sub
    

    Set Dictionary Object “_get” to querystring key value pair collection by extract_querystring(e.Url.Query).
    Get id of deleted person name with simple _get(“id”) to execute DeleteName(_get(“id”)).
    Run this project again and see the result.

Regards,
Agung Gugiaji

Advertisements

3 responses to “Using VB .Net WebBrowser Control To Build WinForm User Interface

  1. Pingback: WinForm Model View Controller Using VB.Net WebBrowser Control | Enlighten Application Developer Journals

  2. adeosun olaniyi julius

    Under private sub AddName, I can’t get “if arrName.count > 0 then …..” To work pls kindly give it another look.

    • Hi,

      Please make sure you have variable declaration & instance creation of arrName.

      arrName var declaration in frmmain class:
      Public Class frmmain
      Dim arrName As SortedDictionary(Of Integer, String)
      End Class
      ‘for dim keyword you can change it to public

      And also arrName instance creation in private sub frmmain_load:

      Private Sub frmmain_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
      arrName = New SortedDictionary(Of Integer, String)
      End Sub

      Thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s