Updating the text on a dynamically generated control In VB - vb.net

I have a dynamically generated TabControl, and am trying to update a Combobox in the TabPage. The function that updates the Combobox is called of a click event.
I've tried to follow some guides regarding manipulating dynamically generated controls by storing the dynamically generated controls as properties on the class: How to pass value from one form to another form's dynamically created control
The controls are generated dynamically as such:
Public Class Form1
Public Sub loadForm()
Dim ctp As New CustomTabPage("Tab number" & i, ErrorList(i), myList, New Object)
Me.myTabControl.TabPages.Add(ctp)
...
End Sub
End Class
Public Class CustomTabPage
Inherits TabPage
Private m_testSelect As ComboBox
...
Public Property testSelect() As ComboBox
Get
testSelect = m_testSelect
End Get
Set(ByVal mytestSelect As ComboBox)
m_testSelect = mytestSelect
End Set
End Property
Public Sub newTab()
m_testSelect = New ComboBox
With m_testSelect
.Location = New System.Drawing.Point(locX + labelSize, locY)
End With
Me.Controls.Add(m_testSelect)
Dim ccb As New CustomCheckBox()
Me.Controls.Add(m_testSelect)
End Sub
Public Sub UpdateCBOs(ByVal i As Integer)
If i = 1 Then
testSelect.Text = "Test1"
ElseIf i = 0 Then
testSelect.Text = "Test2"
End If
...
End Sub
End Class
Public Class CustomCheckBox
Inherits CheckBox
Public Sub Clicked(sender As Object, e As EventArgs) Handles MyBase.CheckedChanged
Dim ctp = CType(Form1.myTabControl.SelectedTab, CustomTabPage)
ctp.UpdateCBOs(i)
End Sub
End Class
Currently while debugging through I stop on the line after line
errorBy.Text = "Test1"
When I mouse over errorBy.Text, and see that errorBy.Text ="" and indeed after the click event finishes, I see on the form that the combobox is not updated.

Related

VB WindowsForm Custom Class Event Handler Issue

I created a custom class (DataGroupBoxControl) that is basically a GroupBox with one or more Panels inside.
Each Panel holds two Labels side by side as pictured below.
enter image description here
The object allows a DataTable to be passed into it, which is what determines how many rows of Panels are created and displayed.
I would like the user to be able to click on one of the Panel Labels and do 'something'.
Here is the procedure inside the class that creates the Labels.
Public Class DataGroupBoxControl
Inherits GroupBox
Public DataLabels As New List(Of DataLabelControl)
Public Sub BindData(ByVal ds As DataTable)
Dim colItem As Integer = 0
For Each col As DataColumn In ds.Columns
DataLabels.Add(New DataLabelControl)
For Each row As DataRow In ds.Rows
DataLabels(colItem).TitleLabel.Text = col.ColumnName & " " & _Separator
DataLabels(colItem).TitleLabel.Name = col.ColumnName
If IsNumeric(row.Item(colItem)) Then
If row.Item(colItem).ToString.IndexOf(".") <> -1 Then
DataLabels(colItem).ValueLabel.Text = Decimal.Parse(row.Item(colItem)).ToString("c")
Else
DataLabels(colItem).ValueLabel.Text = row.Item(colItem)
End If
End If
DataLabels(colItem).ValueLabel.Name = row.Item(colItem)
DataLabels(colItem).Top = (colItem * DataLabels(colItem).Height) + 20
DataLabels(colItem).Left = 5
Me.Controls.Add(DataLabels(colItem))
Me.Height = Me.Height + DataLabels(colItem).Height
DataLabels(colItem).Show()
Next
colItem += 1
Next
End Sub
Where and how do I create a Label Click Event Handler?
And then access that event from my main form with the following object:
Public AccountsGroupBox As New DataGroupBoxControl
Before creating DataLabelControl use AddHandler to attach event handler eg. to TitleLabel control, then you can listen for events and raise new event that can be handled in parent control.
Public Class SomeForm
Private WithEvents AccountsGroupBox As New DataGroupBoxControl
Private Sub AccountsGroupBox_ItemClick(
sender As Object,
args As ItemClickEventArgs) Handles AccountsGroupBox.ItemClick
End Sub
End Class
Public Class ItemClickEventArgs
Inherits EventArgs
Public Property Control As Object
End Class
Public Class DataGroupBoxControl
Inherits GroupBox
Public Event ItemClick(sender As Object, args As ItemClickEventArgs)
Public DataLabels As New List(Of DataLabelControl)
Private Sub OnLabelClick(sender As Object, args As EventArgs)
RaiseEvent ItemClick(Me, New ItemClickEventArgs With {.Control = object})
End Sub
Public Sub BindData(ByVal ds As DataTable)
For Each col As DataColumn In ds.Columns
Dim control = New DataLabelControl
AddHandler control.TitleLabel.Click, AddressOf OnLabelClick
DataLabels.Add(control)
' ...
Next
End Sub
End Class

Pass an object from form to another in VB

I have searched through the internet and couldn't find the answer to my problem, but, the issue is that I have 2 forms;
frm_bookManeger
and
frm_addBook
The first one is the main form and has a list of books (named listBook), a TreeView and a button to invoke the second form to add a new book.
After filling in all of the TextBoxes and information of a book, I press "Add". Then, the second form will be closed and all info of that book will be kept in an instance of Book class. The problem is: how can I pass this instance to the first form to store it in listBook.
For example:
If I create a constructor in form 1 to get form 2 then in form 2:
Dim f1 As form1 = New form1(me)
f1.Show()
f2.Close()
I can't do it because form 1 will start up instantly when I start program, and the default right now doesn't have any parameter in OnCreateMainForm():
Protected Overrides Sub OnCreateMainForm()
Me.MainForm = Global.WindowsApplication5.frm1
End Sub
How can I do it?
First form:
Public Class frm_bookManeger
'list of Book
Dim listBook As List(Of Book) = New List(Of Book)
Private frm_addBook As frm_addBook
Public Sub New(frm_addBook As frm_addBook) 'got error
Me.frm_addBook = frm_addBook
End Sub
Second form:
Public Class frm_addBook
Dim Public tempBook As Book = New Book()
'add book
Private Sub btn_add_Click(sender As Object, e As EventArgs) Handles btn_add.Click
tempBook.BookName1 = TextBox_name.Text
tempBook.Author1 = TextBox_author.Text
tempBook.Price1 = TextBox_price.Text
tempBook.Genre1 = TextBox_genre.Text
tempBook.EstablishedDay1 = dtp_established.Value.Date
Dim frm_Mngr As frm_bookManeger = New frm_bookManeger(Me)
End Sub
End Class
Dim frm As New form1
frm.textbox.Text = Me.passing value.Text
frm.Show()
or you can try
Public Class Form1
Private loginLabel As String
Public Sub New(ByVal loginParameter As String)
InitializeComponent()
Me.loginLabel = loginParameter
End Sub
End Class
dim frm as new Form1(label.Text)
Your frm_addBook needs a reference to the instance of frm_bookManeger so that it can use methods in the latter.
That can be done by passing a reference to the current instance of frm_bookManeger to the New constructor of frm_addBook.
Also, you probably want the book adding form to be a dialog form rather than an ordinary form.
I made a simple "Book" class and used a TextBox to display the books, so the first form is this:
Imports System.Text
Public Class frm_BookManager
Dim bookList As List(Of Book)
Public Class Book
Property Name As String
Property Author As String
End Class
Public Sub AddBook(b As Book)
If bookList Is Nothing Then
bookList = New List(Of Book)
End If
bookList.Add(b)
End Sub
Private Sub ShowBooks()
Dim sb As New StringBuilder
For Each b In bookList
sb.AppendLine(b.Name & " by " & b.Author)
Next
TextBox1.Text = sb.ToString()
End Sub
Private Sub btn_add_Click(sender As Object, e As EventArgs) Handles btn_add.Click
Using addBook As New frm_addBook(Me)
Dim result = addBook.ShowDialog()
If result = DialogResult.OK Then
ShowBooks()
End If
End Using
End Sub
Private Sub frm_BookManager_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AddBook(New Book With {.Name = "Wuthering Heights", .Author = "Emily Brontë"})
ShowBooks()
End Sub
End Class
For the form to add a book, I added "Cancel" and "OK" buttons.
Public Class frm_addBook
Dim myParent As frm_BookManager
Private Sub bnOK_Click(sender As Object, e As EventArgs) Handles bnOK.Click
Dim b As New frm_BookManager.Book With {.Name = TextBox_name.Text, .Author = TextBox_author.Text}
myParent.AddBook(b)
End Sub
Public Sub New(parent As frm_BookManager)
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
myParent = parent
' set the DialogResult for each button so the parent can tell what happened
bnCancel.DialogResult = DialogResult.Cancel
bnOK.DialogResult = DialogResult.OK
End Sub
End Class
Notice that a new Book can be added with myParent.AddBook(b) because myParent refers to an instance of frm_BookManager.
You could modify it so that the dialog stays open and has a button to just add a book and not close the dialog. I made the ShowBooks() method Private so you can't call it from outside the class it is in - you could modify that.
There are many possibilities for small modifications to the code I showed to achieve greater functionality. And I could not resist correcting the spelling of "Maneger" to "Manager" ;)
I think the easiest way would be to have the frm_addBook form have a property which will contain the book that was added. In the frm_bookManager form, show that form using ShowDialog and if the user clicks OK on that form, the property will contain the book added. Be sure to dispose the frm_addBook form after you get the book from the public property.
Public Class Book
Public Property Name As String
Public Property Author As String
End Class
Public Class frm_bookManager
Dim bookList As New List(Of Book)()
Private Sub btnAddBook_Click(sender As Object, e As EventArgs) Handles btnAddBook.Click
Using addBookForm As New frm_addBook()
If addBookForm.ShowDialog() = DialogResult.OK Then
bookList.Add(addBookForm.BookToAdd)
End If
End Using
End Sub
End Class
Public Class frm_addBook
Public Property BookToAdd As Book
Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles
'User filled in the fields and clicked this OK button
Me.BookToAdd = New Book()
Me.BookToAdd.Name = txtName.Text
Me.BookToAdd.Author = txtAuthor.Text
End Sub
End Class
I would not pass the main form instance into the add book form because it would create a tight coupling between the two forms and the add book form would only be usable by the main form. You might wish to use the add book form from other forms in the app.

Passing data between forms DIRECTLY

I'm making a "Preference form" that will hold all the users preferences and when they go to Apply/Save I want the new values to transfer back to the main form and updateand close the form2. In the past I have done this like this:
Private Sub PreferencesToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles PreferencesToolStripMenuItem.Click
Preferences.Show()
End Sub
and when I click the "Apply/Save" button before it closes I would Transfer all data like this:
form1.textbox.text = form2.textbox.text
Is there anything wrong doing it this way??
What I have been reading is I should be doing it like this:
Private Sub PreferencesToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles PreferencesToolStripMenuItem.Click
Dim dialog As New Preferences
dialog.ShowDialog()
End Sub
And when when they click "Apply/Save" it would take all the values from Form2 and store them in a private variable (or Property) in Form2 and when that form closes I would then access the value like this:
Private Sub PreferencesToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles PreferencesToolStripMenuItem.Click
Dim dialog As New Preferences
dialog.ShowDialog()
form1.textbox.text = dialog.variable
End Sub
Why would this be a better way of doing this?
UPDATE....Looking at the code below this is just a SMALL sample of all the options I will have. What is the best way to collect of the data into the object to use when serializing?
<Serializable>
Public Class Preference
#Region "Properties"
Public Property ScaleLowest As String = "5"
Public Property ScaleHighest As String = "200"
Public Property ScaleInc As String = "5"
Public Property ThickLowest As Double = 0.125
Public Property ThickHighest As Double = 4
Public Property ThickInc As Double = 0.125
Public Property WidthLowest As Double = 0.125
Public Property WidthHighest As Double = 0.6
Public Property WidthInc As Double = 0.125
Public Property LengthLowest As Double = 1
Public Property LengthHighest As Double = 96
Public Property LengthInc As Double = 1
Public Property FractionON As Boolean = False
Public Property DecimalON As Boolean = True
Public Property ColorSelection As String = "Colors"
Public Property FinalColor As String = "255, 255, 0"
Public Property roughColor As String = "255, 255, 100"
Public Property SplashON As Boolean = False
Public Property LogInON As Boolean = False
#End Region
Public Sub New()
'for creating new instance for deserializing
End Sub
Public Sub GatherAllData()
'Save Defaults
SaveSerializeObj()
End Sub
Public Sub SaveSerializeObj()
'Get Changes?????
'Serialize object to a text file.
Dim objStreamWriter As New StreamWriter("C:\Users\Zach454\Desktop\test.xml")
Dim x As New XmlSerializer(Me.GetType)
x.Serialize(objStreamWriter, Me)
objStreamWriter.Close()
End Sub
Public Function LoadSerializeObj() As Preference
'Check if new file need created
If File.Exists("C:\Users\454\Desktop\test.xml") = False Then
SaveSerializeObj()
End If
'Deserialize text file to a new object.
Dim objStreamReader As New StreamReader("C:\Users\454\Desktop\test.xml")
Dim newObj As New Preference
Dim x As New XmlSerializer(newObj.GetType)
newObj = CType(x.Deserialize(objStreamReader), Preference)
objStreamReader.Close()
Return newObj
End Function
The best option is to create a class that would have properties for your form controls. Then you can store these properties and then access these when needed.
Also there's really no reason to be passing data back and forth, you can store this data off somewhere (database, file, mysettings etc) and then load this data up into a class. Then you can store and retrieve data from this class. Then if you need to save data back to somewhere you have a class object to use.
Here is a short example to show how you can create another form (Preferences) click save and then show those values back on the other form (calling form).
This is the main form
Public Class Form1
Public _frm2 As Form2
Private Sub btnShowPreferences_Click(sender As Object, e As EventArgs) Handles btnShowPreferences.Click
Using _frm2 As New Form2()
'if we clicked save on the form then show the values in the
'controls that we want to
If _frm2.ShowDialog() = Windows.Forms.DialogResult.OK Then
txtFirstName.Text = _frm2._Preferences.FirstName
txtLastName.Text = _frm2._Preferences.LastName
End If
End Using
End Sub
End Class
Here is an example (Preferences) class
This class would hold all your properties for the preferences. This is an example, you can change anything you need to suit your needs.
Option Strict On
Public Class Preferences
#Region "Properties"
Public Property FirstName As String
Public Property LastName As String
#End Region
Public Sub New()
End Sub
End Class
The second Form could be your (Preference) form with all the controls a user would need to interact with.
Public Class Form2
Public _Preferences As New Preferences 'create class variable you can use for later to store data
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
'set your properties of the class from your form. this will then hold everything you can get from
'the first form...
With _Preferences
.FirstName = txtFirstName.Text
.LastName = txtLastName.Text
End With
Me.DialogResult = Windows.Forms.DialogResult.OK 'this is used to determine if user clicked a save button...
End Sub
End Class
I hope this get's you started, if you do not understand something please let me know.
To directly answer your question, the main difference in your two code samples is that the second uses ShowDialog to open the form modally, vs the first sample which lets you interact with the parent form while the second is open.
The second approach may be better from the view of user flow control. If your real question is whether to push data back to the main form or pull data from the dialog, it is probably better to pull from the dialog. This approach makes the dialog reusable from other forms.

Set the textbox value of usercontrol from Main winForm Button

I have a main Form 'frmMaster' that contains on one button 'btnSet',
inside this main form I put a panel control contains on usercontrol,
on this user control there is one textbox,
my question is how to set the value of this textbox when I click on the button 'btnset' from main form,
for example: when I click on 'btnset' from main form, the value of textbox on the usercontrol will be "Welcome"
In userControl I Put:
Public Property TextBoxTxt () As String
Get
Return txtText1.Text
End Get
Set(value As String)
txtText1.Text = value
End Set
End Property
On Main Form I Put inside button:
Dim uc As New ucControl1
uc.txtText1.Text= "Welcome!"
Your UserControl Must be like :
Public Class UserControl1
Private Sub UserControl1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Public Property TextBoxTxt() As String
Get
Return txtText1.Text
End Get
Set(value As String)
txtText1.Text = value
End Set
End Property
End Class
In you MainForm add a button "btnSet" and a Panel "Panel1" ,so your code inside MainForm must be like :
Public Class frmMaster
Private Sub btnSet_Click(sender As Object, e As EventArgs) Handles btnSet.Click
Dim uc As New UserControl1
uc.txtText1.Text = "Welcome!"
Panel1.Controls.Add(uc)
End Sub
Private Sub frmMaster_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
End Class
I have create a simple exemple for you
In the user control:
Public Property TextBoxTxt () As String
Get
Return Me.textbox.Text
End Get
Set(value As String)
Me.txtebox.Text = value
End Set
End Property
In your even click of the button 'btnset' :
Private Sub btnset_Click(sender As Object, e As EventArgs) Handles btnset.Click
Dim uc As New MyUserControl
uc.TextBoxTxt ="Welcome!"
End Sub
You will need to add a public property to the usercontrol, e.g.
Public Property TextBoxMessage As String
Get
Return textbox.Text
End Get
Set(ByVal value As String)
textbox.Text = value
End Set
End Property
Then you can display a message from inside your frmMaster:
usercontrol.TextBoxMessage = "Welcome!"

How to get inherited type of Form in ControlDesigner

I am building a custom designer that will associate a control with a business property on the form. The form DealUI has properties Instrument and Product, which are a business items:
Public Class DealUI
Inherits System.Windows.Forms.Form ' repetition of Inherits in Deal.Designed.vb, just to make the point
Sub New()
InitializeComponent()
End Sub
<Business(True)> _
Public Property Product As String
<Business(True)> _
Public Property Instrument As String
End Class
The Business attribute is simply
NotInheritable Class BusinessAttribute
Inherits Attribute
Private _isBusiness As Boolean
Sub New(isBusiness As Boolean)
_isBusiness = isBusiness
End Sub
End Class
The form contains a custom control, ProductTextBox of type PilotTextBox:
<DesignerAttribute(GetType(PilotControlDesigner)), _
ToolboxItem(GetType(PilotToolboxItem))> _
Public Class PilotTextBox
Inherits TextBox
Public Property Source As String
End Class
In the designer, when the selected control changes to ProductTextbox, I want to populate its Source property with the names of the Form's properties that have the BusinessAttribute (Instrument and Product), the user can then choose between Instrument and Product. The designer code is
Public Class PilotControlDesigner
Inherits ControlDesigner
Private Sub InitializeServices()
Me.selectionService = GetService(GetType(ISelectionService))
If (Me.selectionService IsNot Nothing) Then
AddHandler Me.selectionService.SelectionChanged, AddressOf selectionService_SelectionChanged
End If
End Sub
Private Sub selectionService_SelectionChanged(ByVal sender As Object, ByVal e As EventArgs)
If Me.selectionService IsNot Nothing Then
If Me.selectionService.PrimarySelection Is Me.Control Then
Dim form As Object = DesigningForm()
If form IsNot Nothing Then
For Each prop As PropertyInfo In form.GetType.GetProperties
Dim attr As Attribute = GetCustomAttribute(prop.ReflectedType, GetType(BusinessAttribute), False)
If attr IsNot Nothing Then
' we've found a Business attribute
End If
Next
End If
End If
End If
End Sub
Private Function DesigningForm() As Object ' in fact, a form, or more precisely something that inherits from Form
Dim host As IDesignerHost = CType(Me.Component.Site.GetService(GetType(IDesignerHost)), IDesignerHost)
Dim container As IContainer = host.Container
For Each comp As Component In container.Components
If comp.GetType.IsAssignableFrom(GetType(Form)) Then ' or anything that inherits 'Form'
return comp ' returns a Form, not a Deal!!
End If
Next comp
Return nothing
End Function
End Class
The selected control is a Deal (which inherits from Form), but the component in the designer is a Form, not a Deal (!! in the comment). I need to examine the Instrument and Product properties, which only exist on a Deal.
How can I obtain the Deal object in the designer?