0

Pretty new to programming. I've managed to come up with this to change the colour of a button once it's pressed. I'm trying to get the text of the button which is clicked on by using the string ChosenRoom, however once I come to save, the value of the string is nothing so I must be doing something wrong.

Private Sub ChangeColor(Sender As Object, e As EventArgs)
            Dim SenderButton As Button = Sender 
            If YellowButton IsNot Nothing Then 
                YellowButton.BackColor = Me.BackColor
            End If
            If SenderButton IsNot YellowButton Then 
                SenderButton.BackColor = Color.Yellow 
                ChosenRoom = SenderButton.Text 
            End If

            YellowButton = Sender 
        End If
    End If

This is what I am using to save the string

cmd1.Parameters.Add(New OleDbParameter("Room Number", CType(ChosenRoom, String)))
Matthew
  • 29
  • 5
  • Are you sure that you don't reset the value of _ChosenRoom_ to a blank string somewhere else in your code? This code sets the _ChosenRoom_ only when the SenderButton is not the YellowButton. Good for the first click, but the second click on the same button doesn't enter the second if – Steve Sep 10 '17 at 09:55

1 Answers1

0

Maybe something in this code will help. I put buttons on a form and...

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click, Button2.Click, Button3.Click
        For Each ctr As Control In Controls
            If TypeOf sender Is Button Then
               Dim MyButton As Button = CType(sender, Button)
                If MyButton.Text = "Button2" Then
                    MyButton.BackColor = Color.Red
                    MyButton.Enabled = False
                    Exit For
                End If

            End If
        Next

    End Sub

Notice the Handles clause. If you are not responding to an event but writing your own Sub then you could pass sender as an argument but it looks like you are responding to an Event in which case you need to use a Handles clause. Boy, that did not work. I'll try again

Turned on Option Strict and it didn't like my assuming that sender was a button even though I just checked with TypeOf. Had to CType it to MyButton.

Mary
  • 14,926
  • 3
  • 18
  • 27
  • Now I got it with Ctr+K. The code worked just not the formatting. Sorry! – Mary Sep 10 '17 at 13:40
  • Mary, as far as I can tell your loop does nothing. If sender is Button2, then the loop exits immediately and if it is not, it won't change while you are looping through controls. Was that the start of another approach that got left in? Also, once you have verified sender is a button, you should probably use DirectCast instead of CType. https://stackoverflow.com/questions/3056514/difference-between-directcast-and-ctype-in-vb-net. You can determine the button using "If MyButton is Button2 Then" rather than "If MyButton.Text = "Button2" Then" – Patrick Sep 11 '17 at 10:20