Link to home
Start Free TrialLog in
Avatar of RobertoFreemano
RobertoFreemanoFlag for United Kingdom of Great Britain and Northern Ireland

asked on

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

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
ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of RobertoFreemano

ASKER

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
There's nothing wrong with that...I'd add it at line 4.5.

Are you getting an error?
No error - it just doesn't know what file type to save as... I'll provide screenshot when i get home.

;)
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
Ok, I got printing working - whoots ;)
Yay!  =)

I take it you found the PrintPage() event?...
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
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
hmmm, must be me but both was just try to SaveFileDialog....

my open button is on Form1
my save button is on Form2
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

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 :(
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
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
it must be me... yet again :(
Sorry it's giving you so many fits Roberto.

Can you post all of Form2?
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.
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

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.
*lines #8 and #10 in YOUR post...
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.
...and what is line #38?
37:        Catch ex As Exception
38:                MsgBox("Error code 10!")
39:         End Try
What is the exception though?

Change it to:

        Catch ex As Exception
               MessageBox.Show(ex.ToString)
        End Try
Sorry Mike,

Long day in the office :(
err1.jpg
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?
Actually no,

Come to think of it, I used this from an old project and now that you've pointed it out ;)
Hope that steers you in the right direction!...   =)
Awesome Mike,

You're amazing dude.

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

and it all works ;)

Thanks my friend ;)