Archive for April, 2009

Refresh Treeview From Another Form with vb.net

Good Morning! Well Brett Favre is at it again. He has requested his release from the New York Jets but says he has no intentions of returning “at this time”. Is there any doubt he will be in a Vikings uniform once the season starts? I have just had it with him. The Vikings can have him.

Today’s topic was requested last night. Basically the user wants to update the treeview on another form after the data is updated. Its not complicated. Basically we add an event handler to the original form that handles the update. On the calling form we call that event when the update occurs. Make it a great day!


Join me on Facebook

 

Private Sub CallingForm_AfterUpdate(ByVal Sender As CallingForm, ByVal Item As Object)

        Dim nd As TreeNode

        nd = Me.SearchNodesForHierarchyItem(Me.mytreeview.Nodes, Item.ID)

        If Not nd Is Nothing Then
            nd.Text = Item.Name
            nd.EnsureVisible()
            Me.mytreeview.SelectedNode = nd
        Else
            Me.Refresh()
            nd = Me.SearchNodesForHierarchyItem(Me.mytreeview.Nodes, Item.ID)
            If Not nd Is Nothing Then
                nd.EnsureVisible()
                Me.mytreeview.SelectedNode = nd
            End If
        End If

    End Sub

Private Sub Refresh()

    Try

      Me.mytreeview.Nodes.Clear()

      If Me.cboTree.SelectedKey = 0 Then

        For Each h As Hierarchy In Hierarchy.TMHierarchies

          Dim n As New HierarchyNode(h.Name)

          n.ImageIndex = 0
          n.SelectedImageIndex = n.ImageIndex
          n.Tag = h
          mytreeview.Nodes.Add(n)

          If h.Children.Count > 0 Then
            n.Nodes.Add(New HierarchyItemNode)
          End If

          n.Expand()
        Next

      Else

        Dim h As Hierarchy = New Hierarchy(CInt(Me.cboTree.SelectedKey))

        Dim n As New HierarchyNode(h.Name)

        n.ImageIndex = 0
        n.SelectedImageIndex = n.ImageIndex
        n.Tag = h
        mytreeview.Nodes.Add(n)

        If h.Children.Count > 0 Then
          n.Nodes.Add(New HierarchyItemNode)
        End If

        n.Expand()

      End If

      If Me.mytreeview.GetNodeCount(False) > 0 Then Me.mytreeview.SelectedNode = Me.mytreeview.Nodes(0)

    Catch ex As Exception

    End Try

  End Sub

 

and on the calling form simly call after an update:

Public Event AfterUpdate(ByVal Sender As CallingForm, ByVal Item As Object)

Technorati Tags: ,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,
,,

1 Comment

Scroll Control Into View In Panel with vb.net

Good Morning! This weekend was pretty busy. In addition to my side work and work on my current projects we had meetings with people about the formation of another band, and making plans to do some work on my house this summer.

Today’s topic was asked of me and it can be a little frustrating I guess. Basically we want to scroll within a panel to a particular control within that panel and have that control come into view. Not complicated but it works. Make it a great day!


Join me on Facebook

Public Class Form1
    Public Class MyData
        Public Sub New(ByVal ctl As Control)
            Me.Ctl = ctl
        End Sub
        Public Ctl As Control
        Public Overrides Function ToString() As String
            Return Ctl.Name
        End Function
    End Class
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        For Each ctl As Control In Panel1.Controls
            If TypeOf ctl Is GroupBox Then
                ComboBox1.Items.Add(New MyData(ctl))
            End If
        Next
    End Sub
    Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
        Dim ctl As Control = DirectCast(ComboBox1.SelectedItem, MyData).Ctl
        Panel1.ScrollControlIntoView(ctl)
    End Sub
End Class

Technorati Tags: ,,,,,,,,,,,,,,,,,,
,,

Leave a comment

Format XML with vb.net

Good Morning! Hope all is well in your neck of the woods. I play bass for a band tonight as well as hopefully getting to catch my daughter in a volleyball game. So today’s topic is how to format xml with vb.net. When I was grabbing and displaying the XML string, it came without line breaks and such which made it difficult to read. So my solution is here. It isn’t elegant or cute but it does work. Make it a great day!


Join me on Facebook

Private Function ParseXml(ByVal xml As String) As String
        Dim builder As New System.Text.StringBuilder()
        Dim xmlString As String = xml.Replace(">", ">" & vbCrLf). _
                Replace("</", vbCrLf & "</").Replace(vbCrLf & vbCrLf, vbCrLf).Trim()
        Dim xmlStringArray As String() = xmlString.Split(vbCrLf)
        Dim indent As Integer = 0
        Dim length As Integer = 0
        Dim bracketCount As Integer = 0
        For Each line As String In xmlStringArray
            length += line.Length + 1
            If line.IndexOf("<?xml") = -1 AndAlso _
                length < xmlString.Length Then
                If line.IndexOf("<") > -1 Then bracketCount += 1
                If bracketCount > 1 Then
                    If line.IndexOf("</") > -1 Then
                        indent -= 2
                    Else
                        indent += 2
                    End If
                End If
            End If
            builder.AppendLine(Space(indent) & line.Trim())
            If line.Trim().PadRight(2).Substring(0, 2) = "</" Then _
                indent -= 2
        Next
        Return builder.ToString()
    End Function

Technorati Tags: ,,,,,,,,,,,,,,,

4 Comments

Download an Image into a byte array with vb.net

Good Morning! It was a relaxing weekend of sorts. I figured out a SQL statement for work that was really being a pain in the butt and helped a friend out. Other than that, it was pretty relaxing.

Today’s topic is how to download an image into a byte array using vb.net. Make it a great day!


Join me on Facebook

Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
    Dim client As New WebClient()
    Try
        Dim imagedata As Byte() = client.DownloadData("http://images2.wikia.nocookie.net/wowwiki/images/e/ed/Icon-new-48×48.png")
        Using ms1 As New MemoryStream(imagedata )
            Dim i As New Image(ms1)
            Me.Image= i
        End Using
    Catch ex As SystemException
        Debug.WriteLine(ex.Message)
    End Try
End Sub

Technorati Tags: ,,,,,,,,,,,,,,,,
,,

Leave a comment

Fill Microsoft Word Template from Datatable with vb.net

Good Morning! Not a lot going on here today. As I had mentioned previously, I joined Facebook and I did meet quite a few friends from days gone by. I will be having lunch with one on Saturday so it will be good to see him again. It should be interesting.

Today’s topic is to fill a Microsoft Word template from a datatable. The boss had wanted me to create a email solution which would allow users to drag (or appear to drag) fields into a Microsoft Word document. It had many other applications and this was one of them. Make it a great day!


Join me on Facebook

Dim objSqlDataSet As New DataSet
        Dim myDataTable As New DataTable("mydata")
        myDataTable.Columns.Add("name", GetType(String))
        myDataTable.Columns.Add("phone", GetType(String))
        myDataTable.Columns.Add("zusatz", GetType(String))
        Dim myArray(2) As Object
        For i As Integer = 0 To 100
            myArray(0) = "Name" & i
            myArray(1) = "Phone: " & i
            If i = 10 Or i = 20 Or i = 30 Or i = 40 Or i = 50 Or i = 60 Or i = 70 Then
                myArray(2) = "zusatz: " & i
            End If
            myDataTable.Rows.Add(myArray)
        Next
        objSqlDataSet.Tables.Add(myDataTable)
        Dim myWord As New Microsoft.Office.Interop.Word.Application
        Dim myDataDoc As Microsoft.Office.Interop.Word.DocumentClass = myWord.Documents.Add
        Dim myTable As Microsoft.Office.Interop.Word.Table = myDataDoc.Tables.Add(myWord.ActiveDocument.Range(0, 0), 1, 3)
        myTable.Rows(1).Cells(1).Range.Text = "name"
        myTable.Rows(1).Cells(2).Range.Text = "phone"
        myTable.Rows(1).Cells(3).Range.Text = "zusatz"
        For Each myRow As DataRow In objSqlDataSet.Tables("mydata").Rows
            Dim wRow As Microsoft.Office.Interop.Word.Row = myTable.Rows.Add()
            wRow.Cells(1).Range.Text = myRow.Item("name")
            wRow.Cells(2).Range.Text = myRow.Item("phone")
            If myRow.IsNull("zusatz") = False Then
                wRow.Cells(3).Range.Text = myRow.Item("zusatz")
            End If
        Next
        myDataDoc.SaveAs("C:\Test\WordData.doc")
        myDataDoc.Close()
        Dim myMailMergeDoc As Document = myWord.Documents.Open("C:\Test\MMTest.doc")
        myMailMergeDoc.MailMerge.OpenDataSource(Name:="C:\Test\WordData.doc")
        myMailMergeDoc.MailMerge.Destination = WdMailMergeDestination.wdSendToNewDocument
        myMailMergeDoc.MailMerge.Execute()
        myWord.ActiveDocument.SaveAs("c:\Test\MMResult.doc")
        myWord.Visible = True
        myMailMergeDoc.Close()
        myWord.Quit()
        MsgBox("Complete")


Join me on Facebook

Technorati Tags: ,,,,,,,,,
,,,,,,,,
,,,,,,,,
,,,,,,,,
,,,,,,,,
,,

1 Comment

Read A Binary File with vb.net

Good Morning! I did not sleep well last night. That happens to me often but it was particularly bad last night. And on top of that I have a long list of meetings I have to do today so I can’t be sleepy, disinterested or crabby or even appear to be those. So hoping this day is over quickly is my prayer!

Today’s topic is how to read a binary file with vb.net. I was asked so I decided to make it a blog post. Make it a great day!


Join me on Facebook

Imports System.IO

Public Class IO_Library

  Public Shared Function ReadBinaryData(ByVal path As String) As Byte()

    ‘ Open the binary file.
    Dim streamBinary As New FileStream(path, FileMode.Open)

    ‘ Create a binary stream reader object.
    Dim readerInput As BinaryReader = New BinaryReader(streamBinary)

    ‘ Determine the number of bytes to read.
    Dim lengthFile As Integer = FileSize(path)

    ‘ Read the data in a byte array buffer.
    Dim inputData As Byte() = readerInput.ReadBytes(lengthFile)

    ‘ Close the file.
    streamBinary.Close()
    readerInput.Close()

    Return inputData

  End Function ‘ReadBinaryData’

  Public Shared Function FileSize(ByVal path As String) As Integer

    Dim info As New FileInfo(path)

    Return info.Length

  End Function ‘FileSize’

End Class ‘IO_Library’


Join me on Facebook

Technorati Tags: ,,,,,,,,,,,,,,,,,,,
,,,,,,,,

Leave a comment

Remove Links From A String (Or Web Page) with vb.net

Good Morning! Last night my daughter totally kicked but at volleyball. She rocked. She really does has potential to be good at this game. As for me, I wrote code to produce a template class for work, where many of the classes generated follow a similar pattern. It was easier to do it this way than to type out the class by hand which had been done previously. Just insane no doubt about it.

Today’s topic requires one line of code! That’s right just one line. Lets say you have downloaded a web page and you want to remove the links from the string but leave the text of the link behind. This little regular expression will do the trick! Don’t forget to import System.RegularExpressions! Make it a great day!

Imports System.Text.RegularExpressions

System.Text.RegularExpressions.Regex.Replace(yourstring, "</?a[^>]*>", String.Empty)


Join me on Facebook

Technorati Tags: ,,,,,,,,,,,,,,,,,,,

3 Comments

Alyssa’s Retro Party

Leave a comment

Get Number of Pages in a Microsoft Word Document with vb.net

Good Morning! Last night I played with the band from Celebrate Recovery. It was okay considering we had never played together and I didn’t know the material. I am not usually in the habit of this, but hey its not rocket science we are doing here. And I only played bass on my keyboard which is pretty easy for me.

Today’s topic is how to get the number of pages in a Microsoft Word document with vb.net. Not complicated, but I was asked so here it is. Make it a great day!


Join me on Facebook

Function GetWordPages

Try
            word_server = New Word.Application
            Dim Doc As Word.Document
            Doc=word_server.Documents.Open(FilePath)
            return Doc.ComputeStatistics(wdStatisticPages)           
        Catch ex As Exception

        Finally
            word_server.Application.Quit()
            word_server = Nothing
        End Try

 

End Function


Join me on Facebook

Technorati Tags: ,,,,,,,,,
,,,,,,,,
,

Leave a comment

A Multi Color Label (actually a RichTextBox) with vb.net

Good Morning! I watched my daughter triumph in her first volleyball game of the year. And she is really GOOD! Actually the whole team had their fundamentals down pretty good. They are going to be quite good if they play together a lot.

Today’s topic comes courtesy of a reader who requested help to make a label …. multi colored. They want to be able to change the fonts and colors of words within the label. I didn’t really get into exactly why because I didn’t;t really want to know.  Coding like this usually turns me off because it serves no useful purpose. So instead of using a label, I recommended a rich text box using the code below. Make it a great day!


Join me on Facebook

”’ <summary>
    ”’ sets a form’s title to a standard – Dual Color title
    ”’
    ”’ for each form that you want to have a standard title on, you only need to:
    ”’ a) drop a RichTextBox on your form, with a meaningful name and suitable properties [Appearance(Font)] / [Layout(Anchor),(Dock),(Size)], and
    ”’ b) call this subroutine which uses armor plate text and colors found in the application’s settings.
    ”’
    ”’ To use, place this subroutine in a standard module to which you have access from a given form’s code
    ”’ 1. add an Application setting called ‘FormTitle’, type of ‘String’, value of whatever you like
    ”’ 2. add an Application setting called ‘FormTitleForeColor’, type of ‘System.Drawing.Color’, value of whatever color you like
    ”’ 3. add an Application setting called ‘FormTitleSubstring’, type of ‘String’, value of the substring in the title to have a new color
    ”’ 4. add an Application setting called ‘FormTitleSubstringForeColor’, type of ‘System.Drawing.Color’, value of substring’s color
    ”’ 5. Add a RichText Box control to your form. 
    ”’ 6. give it a meaningful name for use in your code, such as: rtbSample
    ”’ 6. set rtbSample properties as you normally would., i.e. some text, sizing, etc.  don’t forget to perhaps dock it.
    ”’ 7. in the form’s load procedure:
    ”’ InitializeFormTitle(Me.rtbSample)
    ”’ </summary>
    ”’ <param name="pRtb"></param>
    ”’ <remarks></remarks>

    Public Sub InitializeFormTitle(ByVal pRtb As RichTextBox)
        If (My.Settings.PropertyValues("FormTitle") IsNot Nothing) AndAlso (My.Settings.PropertyValues("FormTitleForeColor") IsNot Nothing) Then
            pRtb.Text = My.Settings.FormTitle.Trim
            pRtb.ReadOnly = True
            pRtb.Enabled = False
            pRtb.BorderStyle = BorderStyle.None
            pRtb.SelectAll()
            pRtb.SelectionAlignment = HorizontalAlignment.Center
            pRtb.SelectionColor = My.Settings.FormTitleForeColor
            pRtb.SelectionFont = New Font(pRtb.SelectionFont, FontStyle.Bold)
            If (My.Settings.PropertyValues("FormTitleSubstring") IsNot Nothing) AndAlso (My.Settings.PropertyValues("FormTitleSubstringForeColor") IsNot Nothing) Then
                If My.Settings.FormTitleSubstring.Trim.Length > 0 Then
                    Dim m_x As Integer
                    m_x = My.Settings.FormTitle.IndexOf(My.Settings.FormTitleSubstring.Trim)
                    If m_x > -1 Then
                        pRtb.Select(m_x, My.Settings.FormTitleSubstring.Trim.Length)
                        pRtb.SelectionColor = My.Settings.FormTitleSubstringForeColor
                        pRtb.SelectionFont = New Font(pRtb.SelectionFont, FontStyle.Bold)
                    End If
                End If
            End If
            pRtb.DeselectAll()
        End If
    End Sub


Join me on Facebook

Technorati Tags: ,,,,,,,,,
,,,,,,,,
,,,,,,,,
,,,,,,,,
,,,,,,,,
,,,,,,,,
,,,

Leave a comment