?
Solved

MDI FORM - Load/Save/Save + Print (if poss) As (VB.NET 2010 Express)

Posted on 2012-09-03
29
Medium Priority
?
968 Views
Last Modified: 2012-09-06
Hi Experts,

I'm trying to create a simple text editor using MDI Form... I've put the code below using my book and an example off the net. I'm struggling to add Sav/SaveAs function to this little project. I'd really appreciate some help ;)

My Form2 has a RTB.

Imports System.IO

Dim xgen As Integer = 0
Public docnum As Integer

Private Sub ToolStripButton1_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripButton1.Click
' New Docs
        Dim forms(xgen) As Form2
        For intloopindex As Integer = xgen To xgen
            forms(intloopindex) = New Form2
            forms(intloopindex).Text = "Doc" & Str(intloopindex)
            forms(intloopindex).MdiParent = Me
            forms(intloopindex).Show()
            xgen = xgen + 1
        Next intloopindex
    End Sub

Private Sub ToolStripButton2_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripButton2.Click
' Open
        Dim fileName As String
        OpenFileDialog1.InitialDirectory = "c:\My Documents"
        OpenFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
        OpenFileDialog1.FilterIndex = 2
        OpenFileDialog1.RestoreDirectory = True
        If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
            fileName = OpenFileDialog1.FileName
        End If
        If fileName = "" Then Exit Sub
        Dim NewMDIChild As New Form2()
        docnum = docnum + 1
        NewMDIChild.MdiParent = Me
        NewMDIChild.Text = fileName
        NewMDIChild.RichTextBox1.LoadFile(fileName, RichTextBoxStreamType.PlainText)
        NewMDIChild.Show()
    End Sub

Open in new window


Also, I would love to know if printing option could be included.

Thanks,
Roberto
0
Comment
Question by:RobertoFreemano
  • 17
  • 12
29 Comments
 
LVL 86

Accepted Solution

by:
Mike Tomlinson earned 1600 total points
ID: 38361928
For saving, you'll want to cast the ActiveMdiChild() to Form2, and call the SaveFile() method against the RichTextBox.

Something like:
    Private Sub ToolStripButton3_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripButton3.Click
        Dim child As Form = Me.ActiveMdiChild
        If Not IsNothing(child) AndAlso TypeOf child Is Form2 Then
            Dim f2 As Form2 = CType(child, Form2)
            If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
                f2.RichTextBox1.SaveFile(SaveFileDialog1.FileName, RichTextBoxStreamType.PlainText)
                MessageBox.Show(SaveFileDialog1.FileName, "File Saved!")
            End If
        End If
    End Sub

Open in new window

0
 

Author Comment

by:RobertoFreemano
ID: 38362435
Wow thanks Mike,

Can I ask silly question...
Q: can a
SaveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"

Open in new window

be added... I tried this but it didn't work... is this because RichTextBox control????

Thanks,
Roberto
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 38362442
There's nothing wrong with that...I'd add it at line 4.5.

Are you getting an error?
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 

Author Comment

by:RobertoFreemano
ID: 38364369
No error - it just doesn't know what file type to save as... I'll provide screenshot when i get home.

;)
0
 

Author Comment

by:RobertoFreemano
ID: 38365100
Thanks Mike, that worked great ;)

I'm just trying to suss out the printer...

I added:
 Private Sub ToolStripButton2_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripButton2.Click
        PrintDialog1.Document = PrintDocument1
        PrintDialog1.PrinterSettings = PrintDocument1.PrinterSettings
        PrintDialog1.AllowSomePages = True
        If PrintDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            PrintDocument1.PrinterSettings = PrintDialog1.PrinterSettings
            PrintDocument1.Print()
        End If

Open in new window

and although I don't have a working printer, it prompts me to save .xps document... but i cannot view it.... am i right in thinking i need to somehow point this to the richtextbox (somehow)?

Thanks,
Roberto
0
 

Author Comment

by:RobertoFreemano
ID: 38365417
Ok, I got printing working - whoots ;)
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 38365443
Yay!  =)

I take it you found the PrintPage() event?...
0
 

Author Comment

by:RobertoFreemano
ID: 38365857
Hi Mike,

one last thing if I may, and forgive me if we've already been over this area...

is there a away to detect if the file is new then SaveFileDialog1
Else
save (write)...

I notice Form1 displays = NewMDIChild.Text = fileName

As you can see by the image... New file create "Document 0"

and Open file shows = "c:\Users\bob\Desktop\web.txt"

is there a way to distinguish this on one floppy button?
Form1.jpg
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 38365980
I would create a field specifically to store the filename, and leave it blank if it is a new document:
Public Class Form2

    Public FileName As String = ""

End Class

Open in new window


So your open code would set that value:

    NewMDIChild.FileName = fileName

Then check that in your save code:

    If f2.FileName <> "" Then
        ' ... overwrite existing file ...
    Else
        ' ... save to a new file ...
    End If
0
 

Author Comment

by:RobertoFreemano
ID: 38366056
hmmm, must be me but both was just try to SaveFileDialog....

my open button is on Form1
my save button is on Form2
0
 

Author Comment

by:RobertoFreemano
ID: 38366061
here's my form1
 
Dim xgen As Integer = 0

    Public docnum As Integer

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

    End Sub

    Private Sub ToolStripButton1_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripButton1.Click

        Dim forms(xgen) As Form2
        For intloopindex As Integer = xgen To xgen
            forms(intloopindex) = New Form2
            forms(intloopindex).Text = "Document " & Str(intloopindex)
            forms(intloopindex).MdiParent = Me
            forms(intloopindex).Show()
            xgen = xgen + 1
        Next intloopindex
    End Sub


    Private Sub ToolStripButton1_MouseEnter(sender As Object, e As System.EventArgs) Handles ToolStripButton1.MouseEnter
        Cursor = Cursors.Hand
    End Sub


    Private Sub ToolStripButton1_MouseLeave(sender As Object, e As System.EventArgs) Handles ToolStripButton1.MouseLeave
        Cursor = Cursors.Default
    End Sub


    Private Sub ToolStripButton2_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripButton2.Click

        Dim fileName As String
        OpenFileDialog1.InitialDirectory = "c:\My Documents"
        OpenFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
        OpenFileDialog1.FilterIndex = 2
        OpenFileDialog1.RestoreDirectory = True
        If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
            fileName = OpenFileDialog1.FileName
        End If
        If fileName = "" Then Exit Sub
        Dim NewMDIChild As New Form2()
        docnum = docnum + 1
        NewMDIChild.MdiParent = Me
        NewMDIChild.Text = fileName
        NewMDIChild.RichTextBox1.LoadFile(fileName, RichTextBoxStreamType.PlainText)
        NewMDIChild.Show()

    End Sub

Open in new window


and Form2

Private PrintPageSettings As New PageSettings
    Private StringToPrint As String
    Private PrintFont As New Font("Arial", 10)
    Dim FileName As String = ""
    Private Sub Form2_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load


    End Sub

    Private Sub ToolStripButton1_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripButton1.Click

        ' Save button

        If FileName <> "" Then
            ' ... overwrite existing file ...
            Try

                Dim iWsave As System.IO.StreamWriter
                iWsave = File.AppendText("c:\esol\profile\_" & "_" & DateString & ".log")
                iWsave.WriteLine(RichTextBox1.Text)
                iWsave.Close()
                MessageBox.Show("File Saved!")
            Catch ex As Exception
                MsgBox("Error code 10!")
            End Try

        Else
            ' ... save to a new file ...
            Dim child As Form = Me.ActiveMdiChild
            SaveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
            If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
                RichTextBox1.SaveFile(SaveFileDialog1.FileName, RichTextBoxStreamType.PlainText)
                MessageBox.Show(SaveFileDialog1.FileName, "File Saved!")
            End If

        End If


    End Sub

    Private Sub ToolStripButton2_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripButton2.Click
        ' Print button

        Try
            'Specify current page settings
            PrintDocument1.DefaultPageSettings = PrintPageSettings
            'Specify document for print dialog box and show
            StringToPrint = RichTextBox1.Text
            PrintDialog1.Document = PrintDocument1
            Dim result As DialogResult = PrintDialog1.ShowDialog()
            'If click OK, print document to printer
            If result = DialogResult.OK Then
                PrintDocument1.Print()
            End If

        Catch ex As Exception
            'Display error message
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
        Dim numChars As Integer
        Dim numLines As Integer
        Dim stringForPage As String
        Dim strFormat As New StringFormat
        'Based on page setup, define drawable rectangle on page
        Dim rectDraw As New RectangleF( _
          e.MarginBounds.Left, e.MarginBounds.Top, _
          e.MarginBounds.Width, e.MarginBounds.Height)
        'Define area to determine how much text can fit on a page
        'Make height one line shorter to ensure text doesn't clip
        Dim sizeMeasure As New SizeF(e.MarginBounds.Width, _
          e.MarginBounds.Height - PrintFont.GetHeight(e.Graphics))

        'When drawing long strings, break between words
        strFormat.Trimming = StringTrimming.Word
        'Compute how many chars and lines can fit based on sizeMeasure
        e.Graphics.MeasureString(StringToPrint, PrintFont, _
          sizeMeasure, strFormat, numChars, numLines)
        'Compute string that will fit on a page
        stringForPage = StringToPrint.Substring(0, numChars)
        'Print string on current page
        e.Graphics.DrawString(stringForPage, PrintFont, _
          Brushes.Black, rectDraw, strFormat)
        'If there is more text, indicate there are more pages
        If numChars < StringToPrint.Length Then
            'Substract text from string that has been printed
            StringToPrint = StringToPrint.Substring(numChars)
            e.HasMorePages = True
        Else
            e.HasMorePages = False
            'All text has been printed, so restore string
            StringToPrint = RichTextBox1.Text
        End If
    End Sub

Open in new window

0
 

Author Comment

by:RobertoFreemano
ID: 38366063
which form do I add:
Public Class Form2
    Public FileName As String = ""
End Class

Open in new window

Please mIke, as it seem to upset other code, no matter where i put it :(
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 38368403
That field should be added to the MdiCHILD Form.

It looks like you attempted with:
Public Class Form2
   Dim FileName As String = ""
End Class

Open in new window


"Dim" at Class defaults to Private, making it inaccessible outside the Class (unless you wrap it in a Public Property).

Change it to Public:
Public Class Form2
   Public FileName As String = ""
End Class

Open in new window


Now, in Form1, you can set that value:

  Private Sub ToolStripButton2_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripButton2.Click

        Dim fileName As String
        OpenFileDialog1.InitialDirectory = "c:\My Documents"
        OpenFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
        OpenFileDialog1.FilterIndex = 2
        OpenFileDialog1.RestoreDirectory = True
        If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
            fileName = OpenFileDialog1.FileName
        End If
        If fileName = "" Then Exit Sub
        Dim NewMDIChild As New Form2()
        docnum = docnum + 1
        NewMDIChild.MdiParent = Me
        NewMDIChild.Text = fileName
       NewMDIChild.FileName = filename
        NewMDIChild.RichTextBox1.LoadFile(fileName, RichTextBoxStreamType.PlainText)
        NewMDIChild.Show()

    End Sub
0
 

Author Comment

by:RobertoFreemano
ID: 38370067
Hi Mike,

I added:
Public Class Form2
        Public FileName As String = ""
    End Class
to Form 2

Open in new window


and:
Private Sub ToolStripButton2_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripButton2.Click ...

Open in new window


to Form1... I now get the error:
Error	1	'Pad.Form2.FileName' is not accessible in this context because it is 'Private'.	C:\Users\bob\documents\visual studio 2010\Projects\Pad\Pad\Form1.vb	53	9	Pad

Open in new window

err.jpg
0
 

Author Comment

by:RobertoFreemano
ID: 38370070
it must be me... yet again :(
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 38370093
Sorry it's giving you so many fits Roberto.

Can you post all of Form2?
0
 

Author Comment

by:RobertoFreemano
ID: 38370102
in Form2 I found declaration of
Dim FileName As String = ""
so I disabled it
' Dim FileName As String = ""

but now, when trying to save an open doc... I get the catch error.
0
 

Author Comment

by:RobertoFreemano
ID: 38370111
Imports System.IO
Imports System.Runtime.InteropServices
Imports System.Drawing.Printing

Public Class Form2


 Public Class Form2
        Public FileName As String = ""
    End Class

    Private PrintPageSettings As New PageSettings
    Private StringToPrint As String
    Private PrintFont As New Font("Arial", 10)

    Property FileName As String

    ' Dim FileName As String = ""
    Private Sub Form2_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load


    End Sub

    Private Sub ToolStripButton1_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripButton1.Click

        ' Save button

        If FileName <> "" Then
            ' ... overwrite existing file ...
            Try

                Dim iWsave As System.IO.StreamWriter
                iWsave = File.AppendText("c:\esol\profile\_" & "_" & DateString & ".log")
                iWsave.WriteLine(RichTextBox1.Text)
                iWsave.Close()
                MessageBox.Show("File Saved!")
            Catch ex As Exception
                MsgBox("Error code 10!")
            End Try

        Else
            ' ... save to a new file ...
            Dim child As Form = Me.ActiveMdiChild
            SaveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
            If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
                RichTextBox1.SaveFile(SaveFileDialog1.FileName, RichTextBoxStreamType.PlainText)
                MessageBox.Show(SaveFileDialog1.FileName, "File Saved!")
            End If

        End If

    End Sub


    Private Sub ToolStripButton2_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripButton2.Click
        ' Print button

        Try
            'Specify current page settings
            PrintDocument1.DefaultPageSettings = PrintPageSettings
            'Specify document for print dialog box and show
            StringToPrint = RichTextBox1.Text
            PrintDialog1.Document = PrintDocument1
            Dim result As DialogResult = PrintDialog1.ShowDialog()
            'If click OK, print document to printer
            If result = DialogResult.OK Then
                PrintDocument1.Print()
            End If

        Catch ex As Exception
            'Display error message
            MessageBox.Show(ex.Message)
        End Try
    End Sub


    Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
        Dim numChars As Integer
        Dim numLines As Integer
        Dim stringForPage As String
        Dim strFormat As New StringFormat
        'Based on page setup, define drawable rectangle on page
        Dim rectDraw As New RectangleF( _
          e.MarginBounds.Left, e.MarginBounds.Top, _
          e.MarginBounds.Width, e.MarginBounds.Height)
        'Define area to determine how much text can fit on a page
        'Make height one line shorter to ensure text doesn't clip
        Dim sizeMeasure As New SizeF(e.MarginBounds.Width, _
          e.MarginBounds.Height - PrintFont.GetHeight(e.Graphics))

        'When drawing long strings, break between words
        strFormat.Trimming = StringTrimming.Word
        'Compute how many chars and lines can fit based on sizeMeasure
        e.Graphics.MeasureString(StringToPrint, PrintFont, _
          sizeMeasure, strFormat, numChars, numLines)
        'Compute string that will fit on a page
        stringForPage = StringToPrint.Substring(0, numChars)
        'Print string on current page
        e.Graphics.DrawString(stringForPage, PrintFont, _
          Brushes.Black, rectDraw, strFormat)
        'If there is more text, indicate there are more pages
        If numChars < StringToPrint.Length Then
            'Substract text from string that has been printed
            StringToPrint = StringToPrint.Substring(numChars)
            e.HasMorePages = True
        Else
            e.HasMorePages = False
            'All text has been printed, so restore string
            StringToPrint = RichTextBox1.Text
        End If
    End Sub

End Class

Open in new window

0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 38370124
I'm surprised that even compiled...you've made an "inner class" of Form2, inside Form2!

Change this:
Public Class Form2

    Public Class Form2
        Public FileName As String = ""
    End Class

    Private PrintPageSettings As New PageSettings
    Private StringToPrint As String
    Private PrintFont As New Font("Arial", 10)

Open in new window


To:
Public Class Form2

    Public FileName As String = ""

    Private PrintPageSettings As New PageSettings
    Private StringToPrint As String
    Private PrintFont As New Font("Arial", 10)

Open in new window


Notice that I removed lines #8 and #10.
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 38370130
*lines #8 and #10 in YOUR post...
0
 

Author Comment

by:RobertoFreemano
ID: 38370179
I removed lines #8 and #10

and #16 flagged up:
Error	2	'FileName' is already declared as 'Public FileName As String' in this class.

Open in new window


If i disable this line....  Line #38 pops up.
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 38370193
...and what is line #38?
0
 

Author Comment

by:RobertoFreemano
ID: 38370201
37:        Catch ex As Exception
38:                MsgBox("Error code 10!")
39:         End Try
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 38370420
What is the exception though?

Change it to:

        Catch ex As Exception
               MessageBox.Show(ex.ToString)
        End Try
0
 

Author Comment

by:RobertoFreemano
ID: 38373806
Sorry Mike,

Long day in the office :(
err1.jpg
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 38373826
I think the error is at this line:

    iWsave = File.AppendText("c:\esol\profile\_" & "_" & DateString & ".log")

Did you really want two underscores "_" right next to each other?
0
 

Author Comment

by:RobertoFreemano
ID: 38373840
Actually no,

Come to think of it, I used this from an old project and now that you've pointed it out ;)
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 38373848
Hope that steers you in the right direction!...   =)
0
 

Author Closing Comment

by:RobertoFreemano
ID: 38373862
Awesome Mike,

You're amazing dude.

I changed to.... "iWsave = File.AppendText(FileName)"

and it all works ;)

Thanks my friend ;)
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In real business world data are crucial and sometimes data are shared among different information systems. Hence, an agreeable file transfer protocol need to be established.
Simulator games are perfect for generating sample realistic data streams, especially for learning data analysis. It is even useful for demoing offerings such as Azure stream analytics, PowerBI etc.
Kernel Data Recovery is a renowned Data Recovery solution provider which offers wide range of softwares for both enterprise and home users with its cost-effective solutions. Let's have a quick overview of the journey and data recovery tools range he…
How to fix display issue, screen flickering issue when I plug in power cord to the machine. Before I start explaining the solution lets check out once the issue how it looks like after I connect the power cord. most of you also have faced this…
Suggested Courses

616 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question