Save a form on generated button click - vb.net

I am trying to insert form fields on a dynamically generated button event. The form is also generated dynamically. However, the submit event handler is not triggering. Here is my code:
Protected Sub BindForm()
'select query for fetching record from database
'dynamically generated button
Dim btnSubmit As New Button()
btnSubmit.ID = "btnSubmit"
btnSubmit.Text = "Save"
AddHandler btnSubmit.Click, AddressOf Me.btnSubmit_click
form1.Controls.Add(btnSubmit)
End Sub
' Dynamic button click event
Protected Sub btnSubmit_click(ByVal sender As Object, ByVal e As EventArgs)
Dim Query As String = "INSERT INTO table column values some_value"
End Sub

You need to create, add, and hookup the event in the OnInit method of the Page. After doing that it will bind the control on post back and fire the event.
Protected Overrides Sub OnInit(e As EventArgs)
Dim btnSubmit As New Button()
btnSubmit.ID = "btnSubmit"
btnSubmit.Text = "Save"
AddHandler btnSubmit.Click, AddressOf Me.btnSubmit_click
form1.Controls.Add(btnSubmit)
End Sub 'OnInit

Related

Add click events to ToolStripTextBox in VB.NET when created in code

I am creating tabs to keep track of open files. When I create them I can set their properties and add them to the list in a MenuStrip.
Before I do so I want to add a click event function. Since this is in a function and will be run multiple times, I need to have a dynamic way to do add these event handlers. I cannot write this:
Private Sub ToolStripTextBox1_Click(sender As Object, e As EventArgs) Handles ToolStripTextBox1.Click
' ...
End Sub
If I do this I can only name them all one name. I want to be able to add a click event that applies to them separately as individual items.
UPDATE:
Dim textFile As ToolStripTextBox = New ToolStripTextBox("textFile")
FileList.Items.Add(textFile)
textFile.Text = filename
textFile.ReadOnly = True
textFile.BackColor = Color.FromArgb(61, 61, 61)
textFile.ForeColor = Color.White
This is the creation and personalization code. Though when you guys suggested AddButton_Click() Handles AddButton.Click It doesn't work because AddButton isn't an actual button
You can keep track of the items, add add and remove click handlers with the following code
Private FileList As New List(Of ToolStripItem)()
' put this code where you add an item
Dim filename = "whatever"
Dim textFile As ToolStripTextBox = New ToolStripTextBox(filename)
textFile.Text = filename
textFile.ReadOnly = True
textFile.BackColor = Color.FromArgb(61, 61, 61)
textFile.ForeColor = Color.White
add(textFile)
Private Sub clickHandler(sender As Object, e As EventArgs)
Dim item = DirectCast(sender, ToolStripItem)
MessageBox.Show(item.Text)
End Sub
Private Sub add(textFile As ToolStripItem)
FileList.Add(textFile) ' Since I don't know what FileList is, I ued List
AddHandler textFile.Click, AddressOf clickHandler
OpenProjectToolStripMenuItem.DropDownItems.Add(textFile) ' add to whatever menu item you normally do
End Sub
Private Sub remove(textFile As ToolStripItem)
FileList.Remove(textFile)
RemoveHandler textFile.Click, AddressOf clickHandler
OpenProjectToolStripMenuItem.DropDownItems.Remove(textFile)
End Sub
The sample click event in your code includes this:
sender As Object
You can re-use this one event handler, because whichever menu item is clicked will be the sender. So you do something like this:
Private Sub ToolStripTextBox1_Click(sender As Object, e As EventArgs) Handles ToolStripTextBox1.Click
Dim menuItem = DirectCast(sender, ToolStripMenuItem)
If menuItem Is Nothing Then Return
'If you need to choose different code for each item:
Select Case menuItem.name
Case "some item"
Case "some other item"
End Select
End Sub
And you can connect your dynamic toolstrip items to this method using AddHandler:
AddHandler myMenuStrip.Click, AddressOf ToolSTripTextBox1_Click

VB: adding object to a tabcontrol tab which doiesnt exist at this time

i want to add a tabcontrol tab by pressing on a button:
Dim inp As String
inp = TextBox6.Text
TabControl2.TabPages.Add(inp)
and when i open this tabpage some object should be already created like a button and a textbox, etc.
i havent found any type of onload events for a tabpage so i tried to add this with:
TabPage8.Controls.Add(New Button())
tabpage8 would be the name of the new created tabpage but like vb already told me, i cant add objects to a tabpage which doesnt exist at that time.
is there any way i can do that or have you any other ideas which could help me?
Your code is close. Try the following:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TabControl2.TabPages.Add("Test")
Dim tp = TabControl2.TabPages(TabControl2.TabPages.Count - 1)
Dim b = New Button()
b.Text = "My Button"
tp.Controls.Add(b)
AddHandler b.Click, AddressOf MyButton_Click
End Sub
Private Sub MyButton_Click(sender As Object, e As EventArgs)
MessageBox.Show("MyButton clicked")
End Sub
This code grabs the last page added and adds a button to it. It also configures the button as needed and adds an event handler.

loop button to check which was clicked

In VB.net form, I have 20 buttons. They are named from btnLoc1 ~ btnLoc20. I do not want to code each button click event.
How to loop through each button to check which was clicked?
Do I need to implement timer tick to listen for button click event?
You can create a single event handler for all the Buttons. Select all the buttons in the designer, open the Properties window, click the Events button and then double-click the Click event. That will generate a Click event handler, just like when you double-click a Button in the designer, except this one will have multiple items in the Handles clause. You can then use the sender parameter to acces the Button that was clicked, e.g.
Private Sub Buttons_Click(sender As Object, e As EventArgs) Handles Button1.Click,
Button2.Click,
Button3.Click
Dim btn = DirectCast(sender, Button)
'Use btn here.
End Sub
The question then is, what do you want to do with that Button? If you want to do something different for each Button then you really should be creating separate event handlers. Alternatively, you might have a list of data and you want to use the item in that list that corresponds to the Button that was clicked. There are numerous ways to do that. One is to put the data in the Tag property of the Button itself and retrieve it from there. Another is to use concurrent indexes, e.g.
Dim buttons = Controls.OfType(Of Button)().ToArray()
Dim data = {"First", "Second", "Third"}
MessageBox.Show(data(buttons.IndexOf(btn)))
Obviously you need to ensure that the Button array and the data array do line up.
For being noticed if button was clicked - eventhandler is best choice.
But you can create only one eventhandler for all buttons
Private Sub Button_Click(sender As Object, e As EventArgs)
Dim button As Button = DirectCast(sender, Button)
MessageBox($"Button '{button.Name}' was clicked")
End Sub
Then in constructor
Public Sub New()
InitializeComponennts()
AddHandler Button1.Click, AddressOf Me.Button_Click
AddHandler Button2.Click, AddressOf Me.Button_Click
AddHandler Button3.Click, AddressOf Me.Button_Click
' and so on
End Sub
If you want to get information about how much each button was clicked, simply create dictionary and add click amount in one eventhandler
Private ButtonsClickAmount As New Dictionary(Of String, Integer)()
Private Sub Button_Click(sender As Object, e As EventArgs)
Dim button As Button = DirectCast(sender, Button)
If ButtonsClickAmount.ContainKey(button.Name) = True Then
ButtonsClickAmount(button.Name) += 1
Else
ButtonsClickAmount.Add(button.Name, 1)
End If
End Sub

Button click on RepositoryItemButtonEdit in gridview doesn't trigger any events in DevExpress

I have a gridview with 3 columns with multiple rows. The first two columns consists of the client's id number and the
client's name. The third column is a RepositoryItemButtonEdit button that, when is clicked, will delete the client from
that row.
I've declared a RepositoryItemButtonEdit the following way.
Dim WithEvents buttonDelete As RepositoryItemButtonEdit
buttonDelete = New RepositoryItemButtonEdit
buttonDelete.TextEditStyle = TextEditStyles.HideTextEditor
buttonDelete.Buttons(0).Kind = ButtonPredefines.Glyph
buttonDelete.Buttons(0).Caption = "Supprimer"
AddHandler buttonDelete.Click, AddressOf Me.Button_Click
I've added it to the third column the following way.
Dim unbColumn As GridColumn = gvException.Columns.AddField("Delete")
unbColumn.VisibleIndex = gvException.Columns.Count
unbColumn.ColumnEdit = buttonDelete
gvException.OptionsView.ShowButtonMode = DevExpress.XtraGrid.Views.Base.ShowButtonModeEnum.ShowAlways
The 'button click' event is captured the following way:
Private Sub Button_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles buttonDelete.Click
MessageBox.Show("Hello world")
end sub
When I launch the application, I see a 'Delete' button for each row.
PROBLEM: However, I only get a 'Hello World' messagebox
when I click on the 'Delete' button from the first row, not when I click on the 'Delete' button from the other rows.
Add buttonDelete.ButtonPressed event instead of buttonDelete.Click event.
What I have tried is below and working fine:
Dim buttonDelete As New RepositoryItemButtonEdit
buttonDelete.Buttons.Clear()
buttonDelete.ButtonsStyle = BorderStyles.UltraFlat
buttonDelete.TextEditStyle = TextEditStyles.HideTextEditor
Dim edtrBtn As EditorButton = New EditorButton()
edtrBtn.Kind = ButtonPredefines.Glyph
edtrBtn.Caption = "Supprimer"
AddHandler buttonDelete.ButtonPressed, AddressOf RepositoryItemButtonEdit_Pressed
buttonDelete.Buttons.Add(edtrBtn)
Pressed event:
Private Sub RepositoryItemButtonEdit_Pressed(sender As Object, e As ButtonPressedEventArgs)
''' Your Logic Here
End Sub
It should work. Rest goes ok.

How to code a Button's Click Event?

I'm using winform and fb.net.
Can someone provide me with an example of how to create a buttons click event?
I have
dim but as windows.forms.button
but.name
but.text
but.location
etc.
but I how do I create the Click and the code behind it?
You can use:
AddHandler button.Click, AddressOf HandlerMethod
In VB you can specify that a method handles a particular event for a particular control, if you're not creating it on the fly - you only need AddHandler when you're (say) dynamically populating a form with a set of buttons.
Here's a short but complete example:
Imports System.Windows.Forms
Public Class Test
<STAThread>
Public Shared Sub Main()
Dim f As New Form()
Dim b As New Button()
b.Text = "Click me!"
AddHandler b.Click, AddressOf ClickHandler
f.Controls.Add(b)
Application.Run(f)
End Sub
Private Shared Sub ClickHandler(sender As Object, e As EventArgs)
Dim b As Button = DirectCast(sender, Button)
b.Text = "Clicked"
End Sub
End Class
EDIT: To close the form, the simplest way is to get the form of the originating control:
Private Shared Sub ClickHandler(sender As Object, e As EventArgs)
Dim c As Control = DirectCast(sender, Control)
Dim f as Form = c.FindForm()
f.Close()
End Sub
In the winforms designer, add a button then double-click it. This will create the event (based on the button's name) and take you to the event's code.