Results 1 to 14 of 14

Thread: Dynamic Creation of Multiple Events for Dynamically Created Control [RESOLVED]

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Oct 2012
    Posts
    166

    Resolved Dynamic Creation of Multiple Events for Dynamically Created Control [RESOLVED]

    Hi again everyone.
    I'm having a really annoying problem here... I've created a textbox dinamically and I'm trying to add more than one event to it.
    As of now I have the TextChanged event working well and I'm trying to add the KeyPress event, but I don't understand what the hell is happening, because the event isn't even fired on debug...

    Summary: I have a feature on my app, where I can change between themes, pretty much like when you change Windows' Themes on Desktop Customization Properties.
    I have currently only the Default VB.Net theme and a custom theme, named Reactor Theme. This pretty much means, that everytime I change themes I need to remove the controls that were associated to the previous theme and create them again, but with the new theme, hence why I need to create controls and their respective events dynamically.

    This is the following code I have to the dynamic control creation and his associated event handlers:

    vb.net Code:
    1. Me.txtBirthDate = New WindowsApplication4.ReactorTextBox()
    2.  
    3. Me.Controls.Remove(txtBirthDate)
    4. Me.txtBirthDate = Nothing
    5. Me.txtBirthDate = New WindowsApplication4.ReactorTextBox()
    6. Me.txtBirthDate.Location = New System.Drawing.Point(127, 38)
    7. Me.txtBirthDate.Name = "txtBirthDate"
    8. Me.txtBirthDate.Size = New System.Drawing.Size(99, 20)
    9. Me.txtBirthDate.TabIndex = 14
    10.  
    11. AddHandler CType(txtBirthDate, WindowsApplication4.ReactorTextBox).TextChanged, AddressOf txtBirthDate_TextChanged
    12. AddHandler CType(txtBirthDate, WindowsApplication4.ReactorTextBox).KeyPress, AddressOf txtBirthDate_KeyPress
    13. Me.ReactorTheme1.Controls.Add(Me.txtBirthDate)

    This is the code I have for the handlers themselves:

    vb.net Code:
    1. Private Sub txtBirthDate_TextChanged(sender As Object, e As EventArgs)
    2.         Try
    3.             If txtName.Text <> String.Empty And txtBirthDate.Text <> String.Empty And txtNationality.Text <> String.Empty _
    4.             And cbGender.SelectedIndex > -1 And txtAddress.Text <> String.Empty And txtZipCode.Text <> String.Empty _
    5.             And txtPhoneNumber.Text <> String.Empty And txtEmail.Text <> String.Empty And cbDepartment.SelectedIndex > -1 _
    6.             And cbAccount.SelectedIndex > -1 And cbEmployeeType.SelectedIndex > -1 Then
    7.                 btnClear.Enabled = True
    8.                 btnRegister.Enabled = True
    9.             Else
    10.                 btnClear.Enabled = False
    11.                 btnRegister.Enabled = False
    12.             End If
    13.         Catch ex As Exception
    14.  
    15.         End Try
    16.  
    17.         Try
    18.             If txtBirthDate.Text.Length >= 3 Then
    19.                 Dim s As String = txtBirthDate.Text.Replace("-", "")
    20.                 For x As Integer = 2 To s.Length Step 2
    21.                     s = s.Insert(x + ((x \ 2) - 1), "-")
    22.                     If x >= 4 Then
    23.                         Exit For
    24.                     End If
    25.                 Next
    26.                 s = s.TrimEnd("-"c)
    27.                 txtBirthDate.Text = s
    28.                 txtBirthDate.SelectionStart = s.Length
    29.             End If
    30.         Catch ex As Exception
    31.  
    32.         End Try
    33.  
    34.         Try
    35.             If CType(txtBirthDate, ReactorTextBox).Text.Length > 10 Then
    36.                 CType(txtBirthDate, ReactorTextBox).Text = CType(txtBirthDate, ReactorTextBox).Text.Remove(CType(txtBirthDate, ReactorTextBox).Text.Length - 1, 1)
    37.             End If
    38.         Catch ex As Exception
    39.  
    40.         End Try
    41.     End Sub
    42.  
    43. Private Sub txtBirthDate_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs)
    44.         MsgBox("FOOBAR")
    45.     End Sub

    This bit of code:

    vb.net Code:
    1. If CType(txtBirthDate, ReactorTextBox).Text.Length > 10 Then
    2.                 CType(txtBirthDate, ReactorTextBox).Text = CType(txtBirthDate, ReactorTextBox).Text.Remove(CType(txtBirthDate, ReactorTextBox).Text.Length - 1, 1)
    3.             End If

    is what I want to take out, because it's unnecessary, when I have a freaking KeyPress event where I only need to point out, that everytime there's 10 characters on the box, I simply forbid the user from typing anything else like so:

    vb.net Code:
    1. If txtBirthDate.TextLength >= 10 Then
    2.         e.Handled = True
    3. End If

    Where's the problem? Well... the code that holds the KeyPress Event is where the problem pretty much is. When I debug the application, with a BreakPoint on the KeyPress event, this event is ignored?!?!
    I know for certain I have the code for the Handlers well designed, I just can't figure out what the hell is missing and there's nothing to point me out a solution, not even a hint.

    Anyone sees at all what am I missing here?
    Last edited by Simbiose; Sep 2nd, 2014 at 09:05 AM.

  2. #2
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,600

    Re: Dynamic Creation of Multiple Events for Dynamically Created Control

    I noticed that you're using both Me.txtBirthDate and txtBirthDate interchangeably in the method where you're wiring up the event handlers. Your AddHandler statements are referencing txtBirthDate and if you have such a variable declared locally then its actually going to be wiring up events for that one which you disposed of earlier and not the new one you've created which you've used Me.txtBirthDate to reference.

    So the real question is: Do you have a local variable named txtBirthDate in that method ?
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  3. #3

    Thread Starter
    Addicted Member
    Join Date
    Oct 2012
    Posts
    166

    Re: Dynamic Creation of Multiple Events for Dynamically Created Control

    Quote Originally Posted by Niya View Post
    I noticed that you're using both Me.txtBirthDate and txtBirthDate interchangeably in the method where you're wiring up the event handlers. Your AddHandler statements are referencing txtBirthDate and if you have such a variable declared locally then its actually going to be wiring up events for that one which you disposed of earlier and not the new one you've created which you've used Me.txtBirthDate to reference.

    So the real question is: Do you have a local variable named txtBirthDate in that method ?
    Thanks for calling that into my atention, it's things like these that easilly missed after so many lines of code x.x
    Nope, "txtBirthDate" is actually a textbox object, which I defined such a name for, so this variable is acessible from anywhere as long as I know how to call it.
    However, I always use the "Me" identifier in order to better help me where I'm standing at the moment, because I have several forms that depend on each other.

    Still, even though I added those missing identifiers, the problem isn't coming from there :s

    Edit* There's also another thing I've noticed. I read on a few forums that people could only get the first of many multiple handlers to be consumed, which led me to think that's what was happening to me, but since that not even the debugger was caring for that handler, it was confusing me.
    To make sure, I commented the TextChanged Event and left only the KeyPress Event to be checked and to my surprise the event was still ignored?!
    I did already check the KeyPreview property, in case anyone's wondering lol and it is set to True, I have no idea what is going on...
    Last edited by Simbiose; Sep 1st, 2014 at 10:32 AM.

  4. #4
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    39,043

    Re: Dynamic Creation of Multiple Events for Dynamically Created Control

    One thing I'd point out is that the code may not work even if the events were working right. It'll work fine if the user is typing into the textbox, but copy/paste may not trigger the events anyways. That's something to look at, but clearly isn't related to the issue.

    The textbox in question is a user control, evidently. What are you doing with the keypress in the user control (as opposed to the application that is making use of the user control)?
    My usual boring signature: Nothing

  5. #5

    Thread Starter
    Addicted Member
    Join Date
    Oct 2012
    Posts
    166

    Re: Dynamic Creation of Multiple Events for Dynamically Created Control

    Quote Originally Posted by Shaggy Hiker View Post
    One thing I'd point out is that the code may not work even if the events were working right. It'll work fine if the user is typing into the textbox, but copy/paste may not trigger the events anyways. That's something to look at, but clearly isn't related to the issue.

    The textbox in question is a user control, evidently. What are you doing with the keypress in the user control (as opposed to the application that is making use of the user control)?
    Since it's a textbox designed for birthdate purposes only, I've planned that textboxes like these will have a maximum of 10 characters and the following format:

    ##-##-####

    I've programmed the TextChanged Event, so that when the user presses the 3rd and 5th number dashes will be written automatically, look below:

    ## (User types 3rd number) => ##-#

    ##-## (User types 5th number) => ##-##-#

    When the textbox reaches 10 characters, the KeyPress Event will and ONLY will handle any key that is currently being pressed. Nothing else will be done by the event, except sending a message to the application informing that the press of the key was handled.

  6. #6
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    39,043

    Re: Dynamic Creation of Multiple Events for Dynamically Created Control

    Ok, an auto-formatting textbox. But what happens on a copy/paste? You get the Textchanged event, but not the KeyPress Event...I think.

    Still, that's beside the point. You may want to post the code modified after the changes you made earlier. I think I know what changes you say you made, but it's a bit distracting to look back at that initial snippet and see the odd stuff with the Me. versus not Me. variables. There's some stuff there that could cause trouble, but it should cause trouble for BOTH events, not just one. It sounds like the TextChanged event is firing as you expect, but not the KeyPress event.

    By the way, is any of that code found in the Load event for the form?
    My usual boring signature: Nothing

  7. #7

    Thread Starter
    Addicted Member
    Join Date
    Oct 2012
    Posts
    166

    Re: Dynamic Creation of Multiple Events for Dynamically Created Control

    Quote Originally Posted by Shaggy Hiker View Post
    Ok, an auto-formatting textbox. But what happens on a copy/paste? You get the Textchanged event, but not the KeyPress Event...I think.

    Still, that's beside the point. You may want to post the code modified after the changes you made earlier. I think I know what changes you say you made, but it's a bit distracting to look back at that initial snippet and see the odd stuff with the Me. versus not Me. variables. There's some stuff there that could cause trouble, but it should cause trouble for BOTH events, not just one. It sounds like the TextChanged event is firing as you expect, but not the KeyPress event.

    By the way, is any of that code found in the Load event for the form?
    Let's get things clearer, at least I hope so lol.
    If the user Copy & Pastes I had already thought about it, but still not worrying about it, as I'm going through everything carefully, but to ease your mind here's what I'll do. I'm gonna add a boolean flag which will check if a user copies any text to the clipboard. If the flag is triggered (i.e. the user copies hence the flag is set to true) then the customization on the TextChanged Event will be disregarded and when the author Pastes the data into the textbox the flag will be reset. I've done this a million times for many things and I'm pretty sure it'll work for this as well.

    Now, about the KeyPress Event that isn't firing, I'll show all the code that plays a part on it. I hope it's not too confusing, here goes:

    My Form Load Event code

    vb.net Code:
    1. Private Sub fEmployeeRegistry_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    2.         Try
    3.             If My.Settings.ThemeModeChosen = 0 Then
    4.                 Me.txtBirthDate = New System.Windows.Forms.TextBox()
    5.                 Me.SuspendLayout()
    6.                 '
    7.                 'txtBirthDate
    8.                 '
    9.                 Me.txtBirthDate.Location = New System.Drawing.Point(127, 38)
    10.                 Me.txtBirthDate.Name = "txtBirthDate"
    11.                 Me.txtBirthDate.Size = New System.Drawing.Size(99, 20)
    12.                 Me.txtBirthDate.TabIndex = 14
    13.                 Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
    14.                 Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
    15.                 Me.ClientSize = New System.Drawing.Size(512, 254)
    16.                 Me.Controls.Add(Me.txtBirthDate)
    17.                 Me.ResumeLayout(False)
    18.                 Me.PerformLayout()
    19.             ElseIf My.Settings.ThemeModeChosen = 1 Then
    20.  
    21.             ElseIf My.Settings.ThemeModeChosen = 2 Then
    22.                 Me.txtBirthDate = New WindowsApplication4.ReactorTextBox()
    23.                 Me.SuspendLayout()
    24.                 '
    25.                 'txtBirthDate
    26.                 '
    27.                 Me.Controls.Remove(Me.txtBirthDate)
    28.                 Me.txtBirthDate = Nothing
    29.                 Me.txtBirthDate = New WindowsApplication4.ReactorTextBox()
    30.                 Me.txtBirthDate.Location = New System.Drawing.Point(127, 38)
    31.                 Me.txtBirthDate.Name = "txtBirthDate"
    32.                 Me.txtBirthDate.Size = New System.Drawing.Size(99, 20)
    33.                 Me.txtBirthDate.TabIndex = 14
    34.  
    35.                 Me.Controls.Remove(Me.ReactorTheme1)
    36.                 Me.ReactorTheme1 = Nothing
    37.                 Me.ReactorTheme1 = New WindowsApplication4.ReactorTheme()
    38.  
    39.                 AddHandler CType(Me.txtBirthDate, WindowsApplication4.ReactorTextBox).TextChanged, AddressOf txtBirthDate_TextChanged
    40.                 AddHandler CType(Me.txtBirthDate, WindowsApplication4.ReactorTextBox).KeyPress, AddressOf txtBirthDate_KeyPress
    41.                 Me.ReactorTheme1.Controls.Add(Me.txtBirthDate)
    42.                 Me.ReactorTheme1.Dock = System.Windows.Forms.DockStyle.Fill
    43.                 Me.ReactorTheme1.Font = New System.Drawing.Font("Verdana", 6.75!)
    44.                 Me.ReactorTheme1.Location = New System.Drawing.Point(0, 0)
    45.                 Me.ReactorTheme1.Name = "fEmployeeRegistry"
    46.                 Me.ReactorTheme1.Text = "fEmployeeRegistry"
    47.                 Me.Size = New System.Drawing.Size(512, 254)
    48.                 Me.ReactorTheme1.Size = Me.Size
    49.                 Me.Controls.Add(Me.ReactorTheme1)
    50.                 Me.ResumeLayout(False)
    51.                 Me.PerformLayout()
    52.             End If
    53.  
    54.             txtBirthDate.MaxLength = 10
    55.             txtZipCode.MaxLength = 8
    56.  
    57.         Catch ex As Exception
    58.  
    59.         End Try

    Note: I just left the code assigned to the txtBirthDate Textbox control. I have many more controls on the Load Event, but no point showing them here for this case.

    My TextChanged Event for the txtBirthDate Textbox control

    vb.net Code:
    1. Private Sub txtBirthDate_TextChanged(sender As Object, e As EventArgs)
    2.         Try
    3.             If txtName.Text <> String.Empty And txtBirthDate.Text <> String.Empty And txtNationality.Text <> String.Empty _
    4.             And cbGender.SelectedIndex > -1 And txtAddress.Text <> String.Empty And txtZipCode.Text <> String.Empty _
    5.             And txtPhoneNumber.Text <> String.Empty And txtEmail.Text <> String.Empty And cbDepartment.SelectedIndex > -1 _
    6.             And cbAccount.SelectedIndex > -1 And cbEmployeeType.SelectedIndex > -1 Then
    7.                 btnClear.Enabled = True
    8.                 btnRegister.Enabled = True
    9.             Else
    10.                 btnClear.Enabled = False
    11.                 btnRegister.Enabled = False
    12.             End If
    13.         Catch ex As Exception
    14.  
    15.         End Try
    16.  
    17.         Try
    18.             If txtBirthDate.Text.Length >= 3 Then
    19.                 Dim s As String = txtBirthDate.Text.Replace("-", "")
    20.                 For x As Integer = 2 To s.Length Step 2
    21.                     s = s.Insert(x + ((x \ 2) - 1), "-")
    22.                     If x >= 4 Then
    23.                         Exit For
    24.                     End If
    25.                 Next
    26.                 s = s.TrimEnd("-"c)
    27.                 txtBirthDate.Text = s
    28.                 txtBirthDate.SelectionStart = s.Length
    29.             End If
    30.         Catch ex As Exception
    31.  
    32.         End Try
    33.  
    34.         Try
    35.             'If CType(Me.txtBirthDate, ReactorTextBox).Text.Length > 10 Then
    36.             '    CType(Me.txtBirthDate, ReactorTextBox).Text = CType(Me.txtBirthDate, ReactorTextBox).Text.Remove(CType(Me.txtBirthDate, ReactorTextBox).Text.Length - 1, 1)
    37.             'End If
    38.         Catch ex As Exception
    39.  
    40.         End Try

    My KeyPress Event for txtBirthDate Textbox control

    vb.net Code:
    1. Private Sub txtBirthDate_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs)
    2.         MsgBox("")
    3.     End Sub

  8. #8
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    39,043

    Re: Dynamic Creation of Multiple Events for Dynamically Created Control

    So, it IS in the Load event. Is that Catch block truly empty? That could be your problem. As you may or may not know, on an increasing number of OS (64-bit, only, I believe), an exception thrown in the Load event will simply be swallowed without any issue...other than that the Load event will appear to exit at that point. By catching exceptions, you'd be getting around that, except that by having an empty catch block you would be swallowing the exceptions. Therefore, if an exception occured on the AddHandler line you'd never know. There wouldn't be any result other than that the event handler wouldn't be hooked up. Still, about the only exception that would be possible would be if the event handler signature was wrong, but it doesn't look wrong.

    Still, if you really do have an empty Catch block in the Load event...don't do that. Put something in there, even if it is just a messagebox showing the exception. You may be getting an exception that you aren't seeing, and the message associated with the exception would be VERY informative, in this case.
    My usual boring signature: Nothing

  9. #9
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,600

    Re: Dynamic Creation of Multiple Events for Dynamically Created Control

    Wait a second, when your ThemeModeChosen is 0 you don't wire up any event handlers, yet you're still creating a TextBox. Why did you do that ?
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  10. #10
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    39,043

    Re: Dynamic Creation of Multiple Events for Dynamically Created Control

    For that matter, the event handlers are only wired up for ThemeModeChosen = 2, as the ThemeModeChosen = 1 is empty.
    My usual boring signature: Nothing

  11. #11

    Thread Starter
    Addicted Member
    Join Date
    Oct 2012
    Posts
    166

    Re: Dynamic Creation of Multiple Events for Dynamically Created Control

    Thank you for the replies.

    On every code block I always start with a Try Catch and one of my objectives at the beggining on my project was to write the exceptions only after I was done with every basic function. However, as my project grew and more ideas were coming to my mind, the problems started to get more and more complex and I had to turn into writting up the Catch blocks in order to solve issues I was having. So, this led to having several Catch blocks without any code and this was on of them lol....

    Once again thanks for pointing me that out. Still, this leaves me a question.
    Even though the Catch block is empty and if there was any error on the AddHandler statement, shouldn't the debugger jump from that very statement to the Catch block?
    I've seen that happen many times on Catch blocks that don't have any code and I was able to check the exception, by hovering the mouse over the found error.
    Anyway, I'm going to write up the code to catch any exceptions and see what that'll lead me to.

    Regarding the ThemeModeChosen variable, when it's value is 0, I haven't set up any handlers, because I'm not testing anything for when the variable has that value, yet.
    So, basically, I'm just debugging the handlers for the code block where the variable ThemeModeChosen has its value set to 2.
    This variable is set at an application global level, more specifically on the Settings tab of the application properties. When the user launches the application, the application itself will check which theme is stored on its setting, through this very variable, so in this case, when I launch the application, I always have the variable set to 2, so that I can debug the handlers.

    Edit* Well, I've set the catch block code and no exception was triggered. It appears that the handle is being added, but then it's ignored...

    Edit** Huhh.... I just moved on into another form and decided to try out theme changing. On the textboxes of that form, the TextChanged Events are triggered, but not the KeyPress Events.
    Then I decided to check the KeyPress Event, but on a ComboBox control that I also have on that form and the event fires! Soooo... hummm?! What is going on here?!
    The code I used on that form is exactly the same.... I'm going insane...
    Last edited by Simbiose; Sep 2nd, 2014 at 05:52 AM.

  12. #12
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,600

    Re: Dynamic Creation of Multiple Events for Dynamically Created Control

    At this point I'd say that the problem is in that ReactorTextbox class. Is that a third party control ? Or is it something you made yourself ?
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  13. #13

    Thread Starter
    Addicted Member
    Join Date
    Oct 2012
    Posts
    166

    Re: Dynamic Creation of Multiple Events for Dynamically Created Control

    Quote Originally Posted by Niya View Post
    At this point I'd say that the problem is in that ReactorTextbox class. Is that a third party control ? Or is it something you made yourself ?
    Well... I was afraid you'd say that and I have been checking that ReactorTheme class in its whole...
    It's a third party class, holds several controls and I have been adjusting the class code to my needs. Apparently I'm missing something on the class itself that blocks or ignores the usage of event like KeyPress.

    Here's the code relevant to the TextBox Control

    vb.net Code:
    1. Public Class ReactorTextBox : Inherits Control
    2.     Dim WithEvents txtbox As New TextBox
    3.  
    4. #Region " Control Help - Properties & Flicker Control "
    5.     Private _passmask As Boolean = False
    6.     Public Property UsePasswordMask() As Boolean
    7.         Get
    8.             Return _passmask
    9.         End Get
    10.         Set(ByVal v As Boolean)
    11.             _passmask = v
    12.             Invalidate()
    13.         End Set
    14.     End Property
    15.     Private _maxchars As Integer = 32767
    16.     Public Shadows Property MaxLength() As Integer
    17.         Get
    18.             Return _maxchars
    19.         End Get
    20.         Set(ByVal v As Integer)
    21.             _maxchars = v
    22.             Invalidate()
    23.         End Set
    24.     End Property
    25.     Private _align As HorizontalAlignment
    26.     Public Shadows Property TextAlign() As HorizontalAlignment
    27.         Get
    28.             Return _align
    29.         End Get
    30.         Set(ByVal v As HorizontalAlignment)
    31.             _align = v
    32.             Invalidate()
    33.         End Set
    34.     End Property
    35.  
    36.     Protected Overrides Sub OnPaintBackground(ByVal pevent As System.Windows.Forms.PaintEventArgs)
    37.     End Sub
    38.     'Protected Overrides Sub OnTextChanged(ByVal e As System.EventArgs)
    39.     '    MyBase.OnTextChanged(e)
    40.     '    'Invalidate()
    41.     'End Sub
    42.     Protected Overrides Sub OnBackColorChanged(ByVal e As System.EventArgs)
    43.         MyBase.OnBackColorChanged(e)
    44.         txtbox.BackColor = BackColor
    45.         Invalidate()
    46.     End Sub
    47.     Protected Overrides Sub OnForeColorChanged(ByVal e As System.EventArgs)
    48.         MyBase.OnForeColorChanged(e)
    49.         txtbox.ForeColor = ForeColor
    50.         Invalidate()
    51.     End Sub
    52.     Protected Overrides Sub OnFontChanged(ByVal e As System.EventArgs)
    53.         MyBase.OnFontChanged(e)
    54.         txtbox.Font = Font
    55.     End Sub
    56.     Protected Overrides Sub OnGotFocus(ByVal e As System.EventArgs)
    57.         MyBase.OnGotFocus(e)
    58.         txtbox.Focus()
    59.     End Sub
    60.     Private _selectedPoint As Integer = 0
    61.     Public Shadows Property SelectionStart() As Integer
    62.         Get
    63.             Return _selectedPoint
    64.         End Get
    65.         Set(ByVal v As Integer)
    66.             _selectedPoint = v
    67.         End Set
    68.     End Property
    69.     Private _selectedLength As Integer = 0
    70.     Public Shadows Property SelectionLength() As Integer
    71.         Get
    72.             Return _selectedLength
    73.         End Get
    74.         Set(ByVal v As Integer)
    75.             _selectedLength = v
    76.         End Set
    77.     End Property
    78.     Sub TextChngTxtBox() Handles txtbox.TextChanged
    79.         Text = txtbox.Text
    80.         txtbox.Select(txtbox.TextLength, 0)
    81.     End Sub
    82.     Sub TextChng() Handles MyBase.TextChanged
    83.         txtbox.Text = Text
    84.         txtbox.Select(txtbox.TextLength, 0)
    85.     End Sub
    86.     Sub NewTextBox()
    87.         With txtbox
    88.             .Multiline = False
    89.             .BackColor = BackColor
    90.             .ForeColor = ForeColor
    91.             .Text = String.Empty
    92.             .TextAlign = HorizontalAlignment.Center
    93.             .BorderStyle = BorderStyle.None
    94.             .Location = New Point(5, 5)
    95.             .Font = New Font("Verdana", 7.25)
    96.             .Size = New Size(Width - 10, Height - 11)
    97.             .UseSystemPasswordChar = UsePasswordMask
    98.             .MaxLength = MaxLength
    99.         End With
    100.  
    101.     End Sub
    102. #End Region
    103.  
    104.     Sub New()
    105.         MyBase.New()
    106.  
    107.         NewTextBox()
    108.         Controls.Add(txtbox)
    109.  
    110.         Text = ""
    111.         BackColor = Color.FromArgb(37, 37, 37)
    112.         ForeColor = Color.White
    113.         Size = New Size(135, 35)
    114.         DoubleBuffered = True
    115.     End Sub
    116.  
    117.     Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
    118.         Dim G As Graphics = e.Graphics
    119.         MyBase.OnPaint(e)
    120.  
    121.         Height = txtbox.Height + 11
    122.         With txtbox
    123.             .Width = Width - 10
    124.             .TextAlign = TextAlign
    125.             .UseSystemPasswordChar = UsePasswordMask
    126.         End With
    127.  
    128.         G.Clear(BackColor)
    129.         G.FillRectangle(New SolidBrush(Color.FromArgb(37, 37, 37)), New Rectangle(1, 1, Width - 2, Height - 2))
    130.         G.DrawRectangle((New Pen(New SolidBrush(Color.Black))), New Rectangle(1, 1, Width - 3, Height - 3))
    131.         G.DrawRectangle((New Pen(New SolidBrush(Color.FromArgb(70, 70, 70)))), New Rectangle(0, 0, Width - 1, Height - 1))
    132.         G.DrawLine(New Pen(New SolidBrush(Color.FromArgb(45, 45, 45))), 0, 0, Width, 0)
    133.         G.DrawLine(New Pen(New SolidBrush(Color.FromArgb(45, 45, 45))), 0, 0, 0, Height)
    134.         G.DrawLine(New Pen(New SolidBrush(Color.FromArgb(45, 45, 45))), Width - 1, 0, Width - 1, Height)
    135.         G.DrawLine(New Pen(New SolidBrush(Color.FromArgb(31, 31, 31))), 2, 2, Width - 3, 2)
    136.     End Sub
    137. End Class

    I still haven't had any luck so far, still only started checking if the problem was coming from the class itself since yesterday ...

    Edit* Well, from what I'm understanding I think I have to instantiate the KeyPress event manually.
    I debugged the class code and everytime a textbox is instantiated on the form that holds that very same textbox, the variable txtbox holds the same control that was instantiated and then that variable is also instantiated, but on the class itself, so what happens here is, since the object was created on the form load event, but has no events attached to it and the object is controlled by the class it appears that I have to create the events within the class.
    For instance, we have the TextChngTxtBox() and TextChng() handle the TextChanged event, where the former handles every textbox that is instantiated on the whole project and the latter handles the object that is called on at a certain point (sub, function, etc) on runtime.
    I'm not sure this is where the problem lies, but the only way to make sure is for me to create the KeyPress event manually on the class and check if this is where the problem lies, but I have no clue on how to do that.
    Last edited by Simbiose; Sep 2nd, 2014 at 08:21 AM.

  14. #14

    Thread Starter
    Addicted Member
    Join Date
    Oct 2012
    Posts
    166

    Re: Dynamic Creation of Multiple Events for Dynamically Created Control

    YES! I finally managed to solve the damn problem!

    I added the KeyPress Event on the ReactorTheme Class itself, like so:

    vb.net Code:
    1. Sub KeyPresTxtBox(sender As Object, e As KeyPressEventArgs) Handles txtbox.KeyPress
    2.         If NumberOfHifens = 1 Then
    3.             If txtbox.TextLength >= 8 Then
    4.                 If Not e.KeyChar = Chr(Keys.Back) Then
    5.                     e.Handled = True
    6.                 End If
    7.             End If
    8.         ElseIf NumberOfHifens = 2 Then
    9.             If txtbox.TextLength >= 10 Then
    10.                 If Not e.KeyChar = Chr(Keys.Back) Then
    11.                     e.Handled = True
    12.                 End If
    13.             End If
    14.         End If
    15.     End Sub

    And I had to add this little bit of code on the TextChng() procedure of the ReactorTheme class:

    vb.net Code:
    1. NumberOfHifens = 0
    2.         For i As Integer = 0 To txtbox.Text.Length - 1
    3.             If txtbox.Text(i) = "-" Then
    4.                 NumberOfHifens += 1
    5.             End If
    6.         Next

    Although I solved the problem, I'm still unaware why the KeyPress Event is only triggered on the class, while the TextChanged Event is triggered in both the form load Event and the class. I'd be really appreciated if someone could explain this to me, because after I've completed my project, I'm gonna lay out every detail, explaining how I did what I did. I'm planning on releasing a website soon explaining the projects I build, so this would be a good remark.

    Edit* I've just realized that the code I had before, was applied to every textbox, because I can't access the KeyPress of a specified Textbox control, precisely because the debugger ignores it (so in a way the problem's still there... and I seriously hope it won't cause further problems in the future...). So I had to write my code on the Event that applies to every textbox Control and in order to differentiate which textboxes I want to have certain formats, all I needed to do was to insert a couple of restrictions on the TextChanged Event at the ThemeReactor class itself, as you can see in the code posted above.
    Last edited by Simbiose; Sep 3rd, 2014 at 04:12 AM.

Posting Permissions

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



Click Here to Expand Forum to Full Width