dcsimg
Results 1 to 26 of 26

Thread: System.InvalidOperationException in Application designer.vb

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Dec 2015
    Location
    Hastings, UK
    Posts
    133

    System.InvalidOperationException in Application designer.vb

    When I run the code the exception stated above stps the code with the following message:
    An error occurred creating the form. The error is: Object variable or with block variable not set. Inner Exception
    NullReferenceException:Object variable or with block variable not set.
    This is the section of the ApplicationDesigner.vb where the exception is.
    Code:
     <Global.System.Diagnostics.DebuggerStepThroughAttribute()>  _
            Protected Overrides Sub OnCreateMainForm()
                Me.MainForm = Global.StringTest.PrintFrm       <<<<<<<<<
            End Sub
    The line where it occurs is marked with chevrons.
    Here is the form code:
    Code:
    Imports PdfSharp
    Imports PdfSharp.Drawing
    Imports PdfSharp.Fonts
    Imports PdfSharp.PageOrientation
    Imports PdfSharp.PageSize
    Imports PdfSharp.Pdf
    Imports PdfSharp.Internal
    Imports PdfSharp.Drawing.Layout
    
    Enum pageOrientation
        Landscape
        Portrait
    End Enum
    Enum Pagesize
        A4
        A5
    End Enum
    Public Class PrintFrm
        Private connectionString As String = "Data Source=DESKTOP-S7FRNAL\SQLEXPRESS;Initial Catalog=Verses_Find;Integrated Security=True"
        Public Property dt As Object
        Private Sub btnPrint_Click(sender As Object, e As EventArgs) Handles btnPrint.Click
            MessageBox.Show(Replace(txbVerse.Text, Chr(13) & Chr(10), " VBCrLf "))
            Dim boxX As Integer
            Dim boxY As Integer
            Dim cellw As Integer
            Dim cellh As Integer
            Dim ort As String = Nothing
            Dim FSize As Integer
            Dim CFont As String = Nothing
            Dim TxtColorValue As String = Nothing
    
            Dim document As PdfDocument
            ' Create a new PDF document
            document = New PdfDocument()
            document.Info.Title = "Created with PDFsharp"
    
            ' Create an empty page
            Dim page As PdfPage = document.AddPage
    
            If ort = "L" Then
                page.Orientation = CType(pageOrientation.Landscape, PdfSharp.PageOrientation)
                page.Width = XUnit.FromMillimeter(297)
                page.Height = XUnit.FromMillimeter(210)
            Else
                page.Orientation = CType(pageOrientation.Portrait, PdfSharp.PageOrientation)
                page.Width = XUnit.FromMillimeter(210)
                page.Height = XUnit.FromMillimeter(297)
            End If
    
    
    
            ' Draw the text
            Dim Ftext As String = txbVerse.Text
    
    
    
            Dim gfx As XGraphics
            gfx = XGraphics.FromPdfPage(page)
            Dim font As XFont = New XFont(CFont, FSize, XFontStyle.Regular)
            Dim tf As XTextFormatter
            tf = New XTextFormatter(gfx)
    
            Dim rect As XRect
            rect = New XRect(boxX, boxY, cellw, cellh)
            gfx.DrawRectangle(XBrushes.SeaShell, rect)
            tf.Alignment = XParagraphAlignment.Center
            tf.DrawString(Ftext, font, XBrushes.Black, rect, XStringFormats.TopLeft)
    
            ' Save the document
            Dim filename As String = "verse.pdf"
            document.Save(filename)
    
            ' ...and start a viewer.
            Process.Start(filename)
        End Sub
    
        Private Sub btnPaste_Click(sender As Object, e As EventArgs) Handles btnPaste.Click
    
            ' Determine if there is any text in the Clipboard to paste into the text box.
            If Clipboard.GetDataObject().GetDataPresent(DataFormats.Text) = True Then
                ' Determine if any text is selected in the text box.
                If txbVerse.SelectionLength > 0 Then
                    ' Ask user if they want to paste over currently selected text.
                    If MessageBox.Show("Do you want to paste over current selection?",
                        "Cut Example", MessageBoxButtons.YesNo) = DialogResult.No Then
                        ' Move selection to the point after the current selection and paste.
                        txbVerse.SelectionStart = txbVerse.SelectionStart +
                            txbVerse.SelectionLength
                    End If
                End If
                ' Paste current text in Clipboard into text box.
                txbVerse.Paste()
            End If
        End Sub
    
        Private Sub PrnForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            'TODO: This line of code loads data into the 'ColorDataSet.TxtColor' table. You can move, or remove it, as needed.
            Me.TxtColorTableAdapter.Fill(Me.ColorDataSet.TxtColor)
            'TODO: This line of code loads data into the 'Verses_Find_Color_DataSet.TxtColor' table. You can move, or remove it, as needed.
            Me.CSizeTableAdapter.Fill(Me.Verses_FindDataSet.CSize)
            Dim Print As New PrintFrm
            Me.TopMost = True
            Me.WindowState = FormWindowState.Normal
    
            For Each oFont As FontFamily In FontFamily.Families 'This line populates the font combo with the system installed fonts
                cboFont.Items.Add(oFont.Name)
            Next
    
        End Sub
    
        Private Sub cboCSize_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboCSize.SelectedIndexChanged
            Me.CSizeTableAdapter.Fill(Me.Verses_FindDataSet.CSize)
            Dim CSizeValue As Integer
            Dim cboCSize As Object = Nothing
            CSizeValue = cboCSize.selectedvalue
        End Sub
    
        Private Sub cboColor_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboColor.SelectedIndexChanged
            Me.TxtColorTableAdapter.Fill(Me.ColorDataSet.TxtColor)
            Dim TxtColorValue As Integer
            Dim cboColor As Object = Nothing
            TxtColorValue = cboColor.selectedvalue
        End Sub
    
        Private Sub nudTop_ValueChanged(sender As Object, e As EventArgs)
            Dim Top As Integer
            Dim nudTop As Object = Nothing
            Top = nudTop.value
        End Sub
    
        Private Sub nudFSize_ValueChanged(sender As Object, e As EventArgs) Handles nudFSize.ValueChanged
            Dim FSize As Integer
            Dim nudFSize As Object = Nothing
            FSize = nudFSize.value
    
    
        End Sub
    
        Private Sub cboFont_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboFont.SelectedIndexChanged
            Dim CFont As String = cboFont.Text
        End Sub
    End Class
    Can someone help me correct this exception,as I can't run the code?

  2. #2
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    103,451

    Re: System.InvalidOperationException in Application designer.vb

    You need to look at the stack trace of the exception to see where it was actually thrown. It almost certainly will not be on the line indicated but rather on a line that gets executed as a result of that line. What will be happening is that the line you indicate causes the default instance of the PrintFrm class to be created, which invokes the constructor of that type, which calls the InitilaizeComponent method of that type, which sets the initial property values for the controls on the form, which will cause various events to be raised, which may invoke one or more of your event handlers. If you have written an event handler under the assumption that it will only be executed because of a user action and thus that certain user input will be available then there's every chance that your issue is that that input is not available when the form is created.

    Any or all of your ValueChanged and SelectedIndexChanged event handlers could be at fault. You need to check that code and make sure that it doesn't make use of any objects that won't exist at that stage. You may want to use a Boolean flag that indicates whether the form is currently being initialised to ensure that none of those event handlers are executed at that stage.

  3. #3

    Thread Starter
    Addicted Member
    Join Date
    Dec 2015
    Location
    Hastings, UK
    Posts
    133

    Re: System.InvalidOperationException in Application designer.vb

    Unfortunately I have Windows 10 version 1803 and according to to Microsoft the call stack feature is not compatible with Windows 10 V. 1709 or later versions.
    What is Windows Driver Kit, is this any help for my problem. It looks like I would have to upgrade Visual Studio to Version 2019!

    If not what next?
    Last edited by Rocky48; Jun 10th, 2019 at 02:40 PM.

  4. #4
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,261

    Re: System.InvalidOperationException in Application designer.vb

    The Stack Trace should be shown on the error dialog automatically, just under the text you quoted at the top of the first post. There should be multiple lines of text, each one starting with the word "at".

    If you post it all here, we can help diagnose the issue.

  5. #5

    Thread Starter
    Addicted Member
    Join Date
    Dec 2015
    Location
    Hastings, UK
    Posts
    133

    Re: System.InvalidOperationException in Application designer.vb

    Sorry I did not realise that you had to be in debug to see the Call Stack. It’s logical when I stopped to think about it.
    Here is the call stack:
    > StringTest.exe!StringTest.PrintFrm.nudFSize_ValueChanged(Object sender, System.EventArgs e) Line 135 Basic
    [External Code]
    StringTest.exe!StringTest.PrintFrm.New() Line 19 Basic
    [External Code]
    How ever this is different to the original error as at the beginning of the post, as I read that the value should be like this:
    FSize = nudFSize.value.ToString
    Here is the complete Sub:
    Code:
    Private Sub nudFSize_ValueChanged(sender As Object, e As EventArgs) Handles nudFSize.ValueChanged
        Dim FSize As Integer = 0
        Dim nudFSize As Object = 24
        FSize = nudFSize.value.ToString
    End Sub
    Here is the error message:
    System.InvalidOperationException
    HResult=0x80131509
    Message=An error occurred creating the form. See Exception.InnerException for details. The error is: Public member 'value' on type 'Integer' not found.
    Source=StringTest
    StackTrace:
    at StringTest.My.MyProject.MyForms.Create__Instance__[T](T Instance) in :line 190
    at StringTest.My.MyProject.MyForms.get_PrintFrm()
    at StringTest.My.MyApplication.OnCreateMainForm() in D:\Visual Basic Projects\StringTest\StringTest\My Project\Application.Designer.vb:line 35
    at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
    at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
    at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
    at StringTest.My.MyApplication.Main(String[] Args) in :line 81

    Inner Exception 1:
    MissingMemberException: Public member 'value' on type 'Integer' not found.
    I hope you can help.

  6. #6
    Fanatic Member
    Join Date
    Nov 2017
    Posts
    853

    Re: System.InvalidOperationException in Application designer.vb

    Code:
    Private Sub nudFSize_ValueChanged(sender As Object, e As EventArgs) Handles nudFSize.ValueChanged
        Dim FSize As Integer = 0
        Dim nudFSize As Object = 24
        FSize = nudFSize.value.ToString
    End Sub
    Against my better judgement, I'm going to enter this thread and ask you to clarify what, exactly, you are attempting to accomplish in this Sub.

    nudFSize appears to be the name of your Numeric Up Down control, so why are you declaring a new variable with the same name? Why is FSize declared as an Integer, and then you are trying to store a String to it? At best, this code would accomplish absolutely nothing, since FSize is declared inside of the Sub, it goes out of scope when the Sub terminates. It's basically, create two variables, give one a value, give that value to the second one in a convoluted way, and then the Sub terminates and both variables disappear.

  7. #7

    Thread Starter
    Addicted Member
    Join Date
    Dec 2015
    Location
    Hastings, UK
    Posts
    133

    Re: System.InvalidOperationException in Application designer.vb

    I am trying to do get the chosen font size from the up down control to use in the PDFSharp class to create a PDF document using form shown at the start of the post. As an inexperienced programmer I am not sure how to get the variables into the PDFSharp print sub from the controls on the form. Do I need to make the various subs Public?

  8. #8
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,261

    Re: System.InvalidOperationException in Application designer.vb

    It is rather concerning that you have so many obvious flaws in that routine (and others like it), especially as you have an appropriate version with txbVerse.

    With txbVerse you didn't create a variable with the same name as the control (you just used the control -creating a variable with the same name only prevents you using the control), and inside the routine you were going to use the value you declared the useful variable (Ftext) and assigned the value to it.


    You should spend some time trying to understand the code you have already got (OptionBase1's comments are things you should have been aware of already), and you should focus on getting just one thing working at a time.

    At the moment you have a mess of lots of unused or inappropriate variables (such as ort), multiple copies of an idea that doesn't work (the events like ValueChanged), and you are pushing on to far more advanced topics like creating PDF files. You are creating a big mess for yourself that you'll need to tidy up later (when its harder to remember what your intentions were), and are getting yourself more confused.

  9. #9

    Thread Starter
    Addicted Member
    Join Date
    Dec 2015
    Location
    Hastings, UK
    Posts
    133

    Re: System.InvalidOperationException in Application designer.vb

    I know I am inexperienced and am trying to push my knowledge far beyond what I know. For a start I am 71 years old and I am trying to use my brain instead of 'vegetating'. If only one of you clever guy's would give me some examples of the the methods I am trying to acheive I may be able to sort out the mess as you so put it. I have tried to find similar examples on the web, but I can't find any that fit my case.

  10. #10
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,261

    Re: System.InvalidOperationException in Application designer.vb

    Your level of experience isn't an issue (we all started like that), neither is your age etc (or the fact you are likely to learn more slowly).

    The issue is that you aren't learning the things that you are already using, and then can't solve the same thing again.


    The example you want is already in your own code, with txbVerse as I alluded to before.

    With txbVerse you only have code inside btnPrint_Click (where you actually want to use the value), and you didn't create a variable with the same name as the control - you just read the value of the control (into a valid variable) and then used it in the call to tf.DrawString :
    Quote Originally Posted by Rocky48
    Code:
            ' Draw the text
            Dim Ftext As String = txbVerse.Text
            ...
            tf.DrawString(Ftext, font, XBrushes.Black, rect, XStringFormats.TopLeft)
    For different controls there are different properties you can read, and using .Text is not normally correct. In the case of nudFSize, it should be like this:
    Code:
        Dim FSize As Integer = nudFSize.value

  11. #11

    Thread Starter
    Addicted Member
    Join Date
    Dec 2015
    Location
    Hastings, UK
    Posts
    133

    Re: System.InvalidOperationException in Application designer.vb

    Thanks Si, but I still get an error!
    'Message=Public member 'Value' on type 'Integer' not found.'

    Code:
     Private Sub nudFSize_ValueChanged(sender As Object, e As EventArgs) Handles nudFSize.ValueChanged
            Dim nudFSize As Integer = 24
            Dim FSize As Integer = nudFSize.Value
        End Sub
    Now what's wrong?

  12. #12
    Fanatic Member
    Join Date
    Nov 2017
    Posts
    853

    Re: System.InvalidOperationException in Application designer.vb

    Please explain what you think this line of code is accomplishing for you:

    Code:
    Dim nudFSize As Integer = 24

  13. #13

    Thread Starter
    Addicted Member
    Join Date
    Dec 2015
    Location
    Hastings, UK
    Posts
    133

    Re: System.InvalidOperationException in Application designer.vb

    I thought that it would default to that value!
    Is that overriding the NumericUpDown input?
    Do I need to delete the =24?

  14. #14
    Fanatic Member
    Join Date
    Nov 2017
    Posts
    853

    Re: System.InvalidOperationException in Application designer.vb

    An analogy.

    Imagine that you always refer to your car as Jessica. That is, except when you are in your bathroom. Inside your bathroom, the word Jessica refers to the number 24 for some unknown but not inappropriate reason.

    Now, if you were in your bathroom, and someone asked you how much mileage Jessica has, your answer is? Ha, what a ridiculous question, the number 24 doesn't have mileage!

    With that line of code you are taking the name that, everywhere else in your code refers to the NUD control, and instead you are making that name refer to the number 24 inside of that Subroutine. And then you are attempting to access the .Value property which would work if you were still referring to the NUD control, but since that name no longer refers to the NUD control but instead to the value 24, you are getting an error message, because an Integer doesn't have a .Value property (nor does it need one, for that matter, since it is a value already).

    Get rid of that line of code completely - it's not like that line of code is close to being right but just needs a minor adjustment - it absolutely makes no sense regardless of what you are actually needing to do in that Subroutine.

    I can't help you any further, but I wish you good luck.
    Last edited by OptionBase1; Jun 14th, 2019 at 05:29 PM.

  15. #15

    Thread Starter
    Addicted Member
    Join Date
    Dec 2015
    Location
    Hastings, UK
    Posts
    133

    Re: System.InvalidOperationException in Application designer.vb

    Thank you OptionBase1
    Having understood your analogy I have corrected the code, but still have other errors.
    I'll post the code here for reference, but I will start a new thread for the new error.
    Code:
    Imports PdfSharp
    Imports PdfSharp.Drawing
    Imports PdfSharp.Fonts
    Imports PdfSharp.PageOrientation
    Imports PdfSharp.PageSize
    Imports PdfSharp.Pdf
    Imports PdfSharp.Internal
    Imports PdfSharp.Drawing.Layout
    Imports System.Data.SqlClient
    Enum pageOrientation
        Landscape
        Portrait
    End Enum
    Enum Pagesize
        A4
        A5
    End Enum
    Public Class PrintFrm
        Private connectionString As String = "Data Source=DESKTOP-S7FRNAL\SQLEXPRESS;Initial Catalog=Verses_Find;Integrated Security=True"
        Public Property dt As Object
        Private Sub btnPrint_Click(sender As Object, e As EventArgs) Handles btnPrint.Click
            MessageBox.Show(Replace(txbVerse.Text, Chr(13) & Chr(10), " VBCrLf "))
            Dim boxX As Integer
            Dim boxY As Integer
            Dim cellw As Integer
            Dim cellh As Integer
            Dim ort As String = Nothing
            Dim FSize As Integer
            Dim CFont As String = Nothing
            Dim TxtColorValue As String
    
            Dim document As PdfDocument
            ' Create a new PDF document
            document = New PdfDocument()
            document.Info.Title = "Created with PDFsharp"
    
            ' Create an empty page
            Dim page As PdfPage = document.AddPage
    
            If ort = "L" Then
                page.Orientation = CType(pageOrientation.Landscape, PdfSharp.PageOrientation)
                page.Width = XUnit.FromMillimeter(297)
                page.Height = XUnit.FromMillimeter(210)
            Else
                page.Orientation = CType(pageOrientation.Portrait, PdfSharp.PageOrientation)
                page.Width = XUnit.FromMillimeter(210)
                page.Height = XUnit.FromMillimeter(297)
            End If
    
    
    
            ' Draw the text
            Dim Ftext As String = txbVerse.Text
    
    
    
            Dim gfx As XGraphics
            gfx = XGraphics.FromPdfPage(page)
            Dim tf As XTextFormatter
            tf = New XTextFormatter(gfx)
    
            Dim rect As XRect
            rect = New XRect(boxX, boxY, cellw, cellh)
            gfx.DrawRectangle(XBrushes.SeaShell, rect)
            tf.Alignment = XParagraphAlignment.Center
            tf.DrawString(Ftext, New XFont(CFont, FSize, XFontStyle.Regular), XBrushes.Black, rect, XStringFormats.TopLeft)
    
            ' Save the document
            Dim filename As String = "verse.pdf"
            document.Save(filename)
    
            ' ...and start a viewer.
            Process.Start(filename)
        End Sub
    
        Private Sub btnPaste_Click(sender As Object, e As EventArgs) Handles btnPaste.Click
    
            ' Determine if there is any text in the Clipboard to paste into the text box.
            If Clipboard.GetDataObject().GetDataPresent(DataFormats.Text) = True Then
                ' Determine if any text is selected in the text box.
                If txbVerse.SelectionLength > 0 Then
                    ' Ask user if they want to paste over currently selected text.
                    If MessageBox.Show("Do you want to paste over current selection?",
                        "Cut Example", MessageBoxButtons.YesNo) = DialogResult.No Then
                        ' Move selection to the point after the current selection and paste.
                        txbVerse.SelectionStart = txbVerse.SelectionStart +
                            txbVerse.SelectionLength
                    End If
                End If
                ' Paste current text in Clipboard into text box.
                txbVerse.Paste()
            End If
        End Sub
    
        Private Sub PrnForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            'TODO: This line of code loads data into the 'ColorDataSet.TxtColor' table. You can move, or remove it, as needed.
            Me.TxtColorTableAdapter.Fill(Me.ColorDataSet.TxtColor)
            'TODO: This line of code loads data into the 'Verses_Find_Color_DataSet.TxtColor' table. You can move, or remove it, as needed.
            Me.CSizeTableAdapter.Fill(Me.Verses_FindDataSet.CSize)
            Dim Print As New PrintFrm
            Me.TopMost = True
            Me.WindowState = FormWindowState.Normal
    
            For Each oFont As FontFamily In FontFamily.Families 'This line populates the font combo with the system installed fonts
                cboFont.Items.Add(oFont.Name)
            Next
    
        End Sub
    
        Private Sub cboCSize_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboCSize.SelectedIndexChanged
            Me.CSizeTableAdapter.Fill(Me.Verses_FindDataSet.CSize)
            Dim cboCSize As Integer
            Dim CSizeValue As Integer = cboCSize
    
        End Sub
    
        Private Sub cboColor_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboColor.SelectedIndexChanged
            ' Me.TxtColorTableAdapter.Fill(Me.ColorDataSet.TxtColor)
            Dim cboColor As Integer
            Dim TxtColorValue As Integer = cboColor
        End Sub
    
        Private Sub nudTop_ValueChanged(sender As Object, e As EventArgs)
            Dim nudTop As Integer
            Dim CTop As Integer = nudTop
    
        End Sub
    
        Private Sub nudFSize_ValueChanged(sender As Object, e As EventArgs) Handles nudFSize.ValueChanged
            Dim nudFSize As Integer
            Dim FSize As Integer = nudFSize
        End Sub
    
        Private Sub cboFont_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboFont.SelectedIndexChanged
            Dim CFont As String = cboFont.Text
        End Sub
    End Class
    The new post will be called 'Object reference not set to an instance of an object'

  16. #16
    Fanatic Member
    Join Date
    Nov 2017
    Posts
    853

    Re: System.InvalidOperationException in Application designer.vb

    Quote Originally Posted by Rocky48 View Post
    Thank you OptionBase1
    Having understood your analogy I have corrected the code
    Great! Wait...

    Quote Originally Posted by Rocky48 View Post
    Code:
        Private Sub nudFSize_ValueChanged(sender As Object, e As EventArgs) Handles nudFSize.ValueChanged
            Dim nudFSize As Integer
            Dim FSize As Integer = nudFSize
        End Sub
    Nope. Good luck.

  17. #17

    Thread Starter
    Addicted Member
    Join Date
    Dec 2015
    Location
    Hastings, UK
    Posts
    133

    Re: System.InvalidOperationException in Application designer.vb

    So I have not understood??
    Have I got it the wrong way around?
    i.e. Dim Fsize as Integer
    Dim nudFSize as Integer = FSize

    If wrong example please?

  18. #18
    Frenzied Member
    Join Date
    Jul 2011
    Location
    UK
    Posts
    1,269

    Re: System.InvalidOperationException in Application designer.vb

    Hi Rocky,

    You already have a variable named nudFSize
    It references a NumericUpDown control on your Form.

    You really do not want to be declaring the variable again as an Integer type (with the line Dim nudFSize As Integer)

    If you want to set the Value property of the NUD, you would use:
    Code:
    nudFSize.Value = 24
    If you want to read the Value property of the NUD, you would use:
    Code:
    Dim Fsize as Integer = CInt(nudFSize.Value)

    However, you would not do that in the ValueChanged event handler in the manner you have it in your code:
    Code:
    Private Sub nudFSize_ValueChanged(sender As Object, e As EventArgs) Handles nudFSize.ValueChanged
        Dim nudFSize As Integer
        Dim FSize As Integer = Cint(nudFSize.Value)
    End Sub
    Variables have scope. As soon as you exit that method any variable you declare in the method will be lost and unretrievable. Take a look at the documentation here for starters.

  19. #19

    Thread Starter
    Addicted Member
    Join Date
    Dec 2015
    Location
    Hastings, UK
    Posts
    133

    Re: System.InvalidOperationException in Application designer.vb

    So I have not understood??
    Have I got it the wrong way around?
    i.e. Dim Fsize as Integer
    Dim nudFSize as Integer = FSize

    If wrong example please?

  20. #20
    Frenzied Member
    Join Date
    Jul 2011
    Location
    UK
    Posts
    1,269

    Re: System.InvalidOperationException in Application designer.vb

    Quote Originally Posted by Inferrd View Post
    You already have a variable named nudFSize
    It references a NumericUpDown control on your Form.
    I meant to explain that, but forgot:

    I'm assuming you dragged a NUD from the toolbox onto the design window and then renamed it as nudFSize in the properties window for the control.

    If so, the VS IDE designer will have created a variable with the same name for you, and scoped it so it is accessible at Form level and thus by all the Form's methods (Subs and Functions).

  21. #21

    Thread Starter
    Addicted Member
    Join Date
    Dec 2015
    Location
    Hastings, UK
    Posts
    133

    Re: System.InvalidOperationException in Application designer.vb

    Forget about #19, I must have posted at the same time as #18!

    The ValueChanged event handler was created when I double clicked on the control.
    So, if I'm correct the form is a Module, therefore any variables I declare in that module will be available to any of the sub-routines.
    How does it change if in a ValueChanged event?
    Could you give me an example?
    Assuming that the way I have written these subs is correct, then:
    I have 2 NUD controls and have changed one like so:
    Code:
     Private Sub nudFSize_ValueChanged(sender As Object, e As EventArgs) Handles nudFSize.ValueChanged
            Dim Fsize As Integer = CInt(nudFSize.Value)
            MessageBox.Show(CStr(FSize))
        End Sub
    The other NUD is similar, but says that nudTop has not been declared??
    Code:
    Private Sub nudTop_ValueChanged(sender As Object, e As EventArgs) 
            Dim CTop As Integer = CInt(nudTop.value)
        End Sub
    Why does the nudTop have the Handles part?
    Why does the FSize one not show the same error?
    I did try as InteliSense suggested, but that still said that nudTop had been used before it had been assigned a value?
    Code:
    Dim nudTop As NumericUpDown = nudTop
    Last edited by Rocky48; Jun 16th, 2019 at 12:21 PM.

  22. #22
    Fanatic Member
    Join Date
    Nov 2017
    Posts
    853

    Re: System.InvalidOperationException in Application designer.vb

    Honestly, your best bet is to find a good online VB.NET programming tutorial, or find a cheap VB.NET programming book on Amazon and start from the beginning. The questions you are asking throw up a bunch of red flags that say "this guy is going to need massive handholding to get his code working", and most of the members here don't have the time and/or patience to do that. Especially when there is no shortage of material available online or in print that will get you on the right track if you put some of your own time and effort into it, and don't assume you already know things.

  23. #23

    Thread Starter
    Addicted Member
    Join Date
    Dec 2015
    Location
    Hastings, UK
    Posts
    133

    Re: System.InvalidOperationException in Application designer.vb

    I have purchased a VB book, but it does not cover all the variations and nether does the material online.
    Most of the answers don't fully explain the code or suggest something but don't give examples.
    However, you would not do that in the ValueChanged event handler in the manner you have it in your code:
    Code:
    Private Sub nudFSize_ValueChanged(sender As Object, e As EventArgs) Handles nudFSize.ValueChanged
    Dim nudFSize As Integer
    Dim FSize As Integer = Cint(nudFSize.Value)
    End Sub
    He did not say how you do it in this case.

  24. #24
    Frenzied Member
    Join Date
    Jul 2011
    Location
    UK
    Posts
    1,269

    Re: System.InvalidOperationException in Application designer.vb

    Quote Originally Posted by Rocky48 View Post
    The ValueChanged event handler was created when I double clicked on the control.
    Yep, and notice that the Handles clause is automatically added for you as well.
    Code:
    Private Sub nudFSize_ValueChanged(sender As Object, e As EventArgs) Handles nudFSize.ValueChanged
    Also notice that the Handles clause is missing for nudTop
    Code:
    Private Sub nudTop_ValueChanged(sender As Object, e As EventArgs)
    That most often happens when you delete the control in the designer window.

    So perhaps you deleted nudTop in the designer and added back a NUD with a slightly different name? If so, double clicking on that control in the designer will create a new ValueChanged event handler code stub specifically for the new control.

    Make sure to get rid of Dim nudTop As NumericUpDown = nudTop if you added that line yourself.



    Quote Originally Posted by Rocky48 View Post
    So, if I'm correct the form is a Module, therefore any variables I declare in that module will be available to any of the sub-routines.
    The Form is actually a Class. They behave slightly differently to Modules, but variables declared at Module or Class level will be available anywhere in that Class/Module.

    Variables declared at procedure level are not available anywhere. They can only be accessed from the method they are declared in. Once you exit that method, the variable is destroyed.

    You declare FSize inside Sub nudFSize_ValueChanged so that version of FSize will not be available anywhere else.

    To declare it at Class level so it is available to all your methods, your code would look something like:
    Code:
    Public Class PrintFrm
    
        Private FSize As Integer
    
        Private Sub nudFSize_ValueChanged(sender As Object, e As EventArgs) Handles nudFSize.ValueChanged
            Fsize = CInt(nudFSize.Value)  '  <---DO NOT use Dim here: 
            '                                          do not want to redeclare the variable at local scope
            MessageBox.Show(CStr(Fsize))
        End Sub
    
        Private Sub btnPrint_Click(sender As Object, e As EventArgs) Handles btnPrint.Click
            MessageBox.Show(Replace(txbVerse.Text, Chr(13) & Chr(10), " VBCrLf "))
            Dim boxX As Integer
            Dim boxY As Integer
            Dim cellw As Integer
            Dim cellh As Integer
            Dim ort As String = Nothing
            ' Dim FSize As Integer <---- DO NOT declare FSize here
            Dim CFont As String = Nothing
            Dim TxtColorValue As String = Nothing
    
            '
            ' code here
            '
    
            Dim font As XFont = New XFont(CFont, FSize, XFontStyle.Regular)
    
            '
            ' code here
            '
        End Sub
    
    End Class
    FSize is declared just the one time at Class level with Private FSize As Integer (you can use Dim if you want, but Private or Public is more usual when declaring fields). It is never dimmed again in any of the Subs, so there is only the one version of it that you can use anywhere.

    Again, I urge you to research the topic of variable scope.

  25. #25
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,261

    Re: System.InvalidOperationException in Application designer.vb

    Quote Originally Posted by Rocky48 View Post
    So, if I'm correct the form is a Module, therefore any variables I declare in that module will be available to any of the sub-routines.
    How does it change if in a ValueChanged event?
    If you declare variables inside a routine (a sub or function), then the variable only exists inside that routine, and only keeps its value until the routine is exited (via End Sub or End Function etc).

    In this case you want the value inside another routine, so you should have the Dim Fsize line inside that other routine. The control will still have the same value as it did when the ValueChanged event ran, so the variable will have the correct value, but it will be available in the place you want to use it.


    The other NUD is similar, but says that nudTop has not been declared??
    Code:
    Private Sub nudTop_ValueChanged(sender As Object, e As EventArgs) 
            Dim CTop As Integer = CInt(nudTop.value)
        End Sub
    It sounds like the control isn't actually called nudTop, so go to the designer (the 'picture' of the form) and check the properties of the control to make sure the name is right.

    As above, you also do not need to use this ValueChanged event, just create the variable inside the routine where you want to use the value.


    I did try as InteliSense suggested, but that still said that nudTop had been used before it had been assigned a value?
    Code:
    Dim nudTop As NumericUpDown = nudTop
    Don't create variables with the same name as a control, that will only cause you problems.

    In terms of the automatic suggestions for fixing errors, while they can be right sometimes, they are often wrong - and can therefore make things worse (in this case, by adding a variable that serves no purpose, and is just adding confusion).

    You should generally only use an automatic suggestion if you already understand it (and the circumstances of the error) well enough to be sure it will solve the problem. If you don't know enough to be sure then you can try it, but if it doesn't completely solve things, undo it and find the solution another way.


    I have purchased a VB book, but it does not cover all the variations and nether does the material online.
    Nothing will ever cover even 1% of the variations, because there are many billions of variations.

    The important thing is that there are "building blocks", and you can put them together in various ways (like Lego).

    A good tutorial or book will teach you the building blocks (such as variables, and controls, and loops), and they are the building blocks you will almost always use, so it is important to understand them properly. Unfortunately at the moment there are signs that you don't understand them well enough.


    edit: it seems that quick break I had while writing was longer than I thought, and Inferrd got in before me (by quite a bit!). I disagree with his suggestion of declaring the variable at class level, because you don't actually need to use the variable outside of btnPrint_Click

    Whenever possible, you should declare variables inside routines, as that helps avoid mistakes.

  26. #26
    Frenzied Member
    Join Date
    Jul 2011
    Location
    UK
    Posts
    1,269

    Re: System.InvalidOperationException in Application designer.vb

    Quote Originally Posted by si_the_geek View Post
    I disagree with his suggestion of declaring the variable at class level, because you don't actually need to use the variable outside of btnPrint_Click

    Whenever possible, you should declare variables inside routines, as that helps avoid mistakes.
    I also disagree with my suggestion to use a Class level variable :-). However, to my mind, Rocky seemed to be having a hard time understanding the difference between local and class level variables, so I wanted to give him an example.

    I can imagine his frustration at trying to get something working while nothing he does seems to work for him. From my perspective, having working code is a good morale boost. It allows you to experiment further, and then introduce better coding practices.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width