Results 1 to 13 of 13

Thread: Is it possible to manually fire event inside an event?

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Aug 2016
    Posts
    279

    Is it possible to manually fire event inside an event?

    Planning to use the keydown event to fire the dgv click event. Is it possible?

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,347

    Re: Is it possible to manually fire event inside an event?

    The only way to raise an event is to use the RaiseEvent statement inside the code of the class of which the event is a member. In cases like the Button.PerformClick method, that method uses the RaiseEvent statement inside the Button class. If you handle the KeyDown event of a DataGridView then your event handler is a member of the form the grid is on, so your code is not in the grid so it can't raise any events of the grid.

    What you could do is create your own class that inherits DataGridView, overrides the OnKeyDown method and calls the OnClick method, which is where the Click event is already raised using a RaiseEvent statement. You can then use your custom control instead of a standard DataGridView.

  3. #3
    Superbly Moderated NeedSomeAnswers's Avatar
    Join Date
    Jun 2002
    Location
    Manchester uk
    Posts
    2,660

    Re: Is it possible to manually fire event inside an event?

    Do you actually just want to run the same code in both events? with out writing that code twice?

    ... or do you really need for some reason to actually trigger the dgv click event ? and if so what is that reason?
    Please Mark your Thread "Resolved", if the query is solved & Rate those who have helped you



  4. #4
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    4,578

    Re: Is it possible to manually fire event inside an event?

    Let's level up. Let's talk about the problem, the bad solution, and how to solve 1,000 varieties of it while making your code look professional. When we're done, you'll think the question seemed silly, along with the most common answer. NeedsSomeAnswers is on the right track.

    Think about what happens when you click a button. You've registered some event handler and it gets called:
    Code:
    Private Sub Button3_Click(...) Handles Button3.click
        MessageBox.Show("This is the 'Save' button! I'm saving the file!")
        ' ...
    End Sub
    Later, you decide to write auto-save. That involves a timer. When the timer ticks, you want to save the file. But right now, the "save the file" code is in the Button3_Click() method. So naturally, it feels like the question is, "How do I click the button programatically?" People jump through all kinds of hoops to answer that. Some might suggest calling the method directly:
    Code:
    Button3_Click(Button3, EventArgs.Empty)
    So long as you make the method public and have a reference to the right form, that works. Others might suggest deriving a new Button that has a method that lets you raise the event. This is pretty convoluted, it usually shows up when dealing with a Control that doesn't have a method like PerformClick(), the other natural suggestion. It's a Button method that raises the Click event.

    But let's think about this. "Save the file" is a thing we want to do in many places. So defining it in "when Button3 is clicked", one of the many places, is creating complexity. Everything in the program has to know about this button, a specific event, and how to make that button raise the specific event. So instead of your auto-save code reading like, "When the timer ticks, save the file", it reads like, "When the timer ticks, get a reference to the active form and click button 3." Is that clear? I don't think so. Once your program gets big enough, you're going to spend more time chasing down which thing does which than actually writing code.

    It turns out it's the "level 1" answer to the question, but there's a much better way.

    SYou should separate the code that does the thing from the individual event handlers that do it. That means if we have "save the file" as a thing we want to do, we write:
    Code:
    Public Sub SaveTheFile()
        MessageBox.Show("I'm saving the file!")
    End Sub
    And the save button:
    Code:
    Private Sub Button3_Click(...) Handles Button3.click
        MessageBox.Show("This is the 'Save' button!")
        SaveTheFile()
    End Sub
    And later, when we want to write auto-save, we don't have to think about raising events:
    Code:
    Private Sub AutosaveTimer_Tick(...) Handles ...
        MessageBox.Show("Auto-Save")
        SaveTheFile()
    End Sub
    And later, when we buy a fancy new SuperButton control that looks gorgeous but doesn't have PerformClick(), we don't have a problem at all.

    This solves every, "How do I make this thing happen when that thing happens?" problem, regardless of which controls have which events.

    So instead of raising a DataGridView event so the Click event handler can be called, move the code that happens when it's clicked to a Sub that you can call from anywhere. Then the question is, "I want the keydown event to do the thing" and those dots are easy to connect.
    This answer is wrong. You should be using TableAdapter and Dictionaries instead.

  5. #5

    Thread Starter
    Hyperactive Member
    Join Date
    Aug 2016
    Posts
    279

    Re: Is it possible to manually fire event inside an event?

    Quote Originally Posted by jmcilhinney View Post
    What you could do is create your own class that inherits DataGridView, overrides the OnKeyDown method and calls the OnClick method, which is where the Click event is already raised using a RaiseEvent statement. You can then use your custom control instead of a standard DataGridView.
    How can I do that?

  6. #6

    Thread Starter
    Hyperactive Member
    Join Date
    Aug 2016
    Posts
    279

    Re: Is it possible to manually fire event inside an event?

    Quote Originally Posted by NeedSomeAnswers View Post
    Do you actually just want to run the same code in both events? with out writing that code twice?

    ... or do you really need for some reason to actually trigger the dgv click event ? and if so what is that reason?
    yes. yes.

    no.no. reason is the question for the answer of my two yes

  7. #7

    Thread Starter
    Hyperactive Member
    Join Date
    Aug 2016
    Posts
    279

    Re: Is it possible to manually fire event inside an event?

    Quote Originally Posted by Sitten Spynne View Post
    .
    Thank you for your answer Sitten, That is what I am currently doing. I'm just asking if my question is possible to be able not to write the same code twice.

  8. #8
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,347

    Re: Is it possible to manually fire event inside an event?

    Quote Originally Posted by earvinnill View Post
    How can I do that?
    I told you to define a class. Do you know how to define a class? If not, have you searched online for information on how to define a class?
    I told you to inherit another class. Do you know how to inherit a class? If not, have you searched online for information on how to inherit a class?
    I told you to override a method. Do you know how to override a method? If not, have you searched online for information on how to override a method?

    Are you seeing a pattern? Each of these tasks is relatively basic and easy to find information on for yourself. You don't need me to explain them all. I'm happy to help with the hard stuff that you try at and fail but I'm not here to explain the basics so you don't have to bother trying.

  9. #9
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,347

    Re: Is it possible to manually fire event inside an event?

    Quote Originally Posted by NeedSomeAnswers View Post
    Do you actually just want to run the same code in both events? with out writing that code twice?
    Quote Originally Posted by earvinnill View Post
    yes. yes.
    Then that's what a method is for: so that you can execute the same code from multiple places. Put the code you want to execute into its own method and then call that method from both event handlers.

  10. #10
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    4,578

    Re: Is it possible to manually fire event inside an event?

    If you're writing a method, the only code you're writing twice is calling the method. You can't reduce things much smaller than that. I'm not certain you're doing what I advocated if you feel like you're repeating code. Could you show me the code you think is duplicated? I bet I could show you how to avoid the duplication better if I saw it.
    This answer is wrong. You should be using TableAdapter and Dictionaries instead.

  11. #11

    Thread Starter
    Hyperactive Member
    Join Date
    Aug 2016
    Posts
    279

    Re: Is it possible to manually fire event inside an event?

    Quote Originally Posted by Sitten Spynne View Post
    If you're writing a method, the only code you're writing twice is calling the method. You can't reduce things much smaller than that. I'm not certain you're doing what I advocated if you feel like you're repeating code. Could you show me the code you think is duplicated? I bet I could show you how to avoid the duplication better if I saw it.
    Example:
    Code:
     Private Sub Button3_Click(...) Handles Button3.click
        MessageBox.Show("This is the 'Save' button!")
        SaveTheFile()
    End Sub
    and I will put these functions: MessageBox.Show("This is the 'Save' button!")
    SaveTheFile()

    inside a keydown. that is why Iam saying it is duplicated.

  12. #12
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,347

    Re: Is it possible to manually fire event inside an event?

    So then, as we have said, put that code inside its own method and then call that method from both the Click event handler of that Button and, if appropriate, the KeyDown event handler of your DataGridView. You already know you can do this because you've already written that SaveTheFile method and are able to call that from elsewhere so this is no different.

  13. #13
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    4,578

    Re: Is it possible to manually fire event inside an event?

    I think maybe you're taking "don't duplicate code" a little too strictly. Let's make it a little more complex to demonstrate.

    Let's say you want a save button to concatenate the contents of three different text boxes, and also replacing any instances of the string "$DATE$" with some timestamp. The obvious wrong way to do it is something like this:
    Code:
    Private Sub btnSave_Click(...) Handles ...
        Dim fullString = TextBox1.Text & TextBox2.Text & TextBox3.Text
        Dim formattedString = fullString.Replace("$DATE$", DateTime.Now.ToString())
        File.WriteAllText("file.txt", formattedString)
    End Sub
    
    Private Sub frmMain_KeyPress(...) Handles ...
        If <ctrl+S was pushed> Then
            Dim fullString = TextBox1.Text & TextBox2.Text & TextBox3.Text
            Dim formattedString = fullString.Replace("$DATE$", DateTime.Now.ToString())
            File.WriteAllText("file.txt", formattedString)
        End If
    End Sub
    We all agree that's duplication so far. Both JMC and I are proposing:
    Code:
    Private Sub btnSave_Click(...) Handles ...
        SaveFile()
    End Sub
    
    Private Sub frmMain_KeyPress(...) Handles ...
        If <ctrl+S was pushed> Then
            SaveFile()
        End If
    End Sub
    
    Private Sub SaveFile()
        Dim fullString = TextBox1.Text & TextBox2.Text & TextBox3.Text
        Dim formattedString = fullString.Replace("$DATE$", DateTime.Now.ToString())
        File.WriteAllText("file.txt", formattedString)
    End Sub
    That's NOT duplication. You cannot easily sidestep that Button.Click and Control.KeyPress are two different events with different kinds of event handlers. So you're going to have to write two different event handler Subs. What you CAN sidestep is that the details of saving a file are the same in either case.

    There is a janky way to write an event handler that can handle ANY event. But since you need to know if it's a KeyPress so you can check the key, you're not going to save any trouble and in fact you might create more by doing so.
    This answer is wrong. You should be using TableAdapter and Dictionaries instead.

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