How to return selected item on listbox on the second form to the main form in visual basic? - vb.net

So basically you have a main form that shows only a label (lblTotalPrice) and a button that when you click it, it opens a second form that contains a listbox with different prices packages (lstPackages). How do do you select an item from lstPackages that is on the second form and return it to lblTotalPrice, which is located on the main form?
I attempted this code using a function (thought it would be useful for calculations), but it seems like it didn't work:
On my second form, I populated the lstPackages with it's name using parallel arrays:
Dim strPackages As String = {"Package 1", "Package 2", "Package 3", "Package 4", "Package 5"}
Dim decPrice As String = {100D, 200D, 300D, 400D, 500D}
Private Sub SecondForm_Activated(sender As Object, e As EventArgs) Handles MyBase.Activate
Dim frmMain as New
Dim i As Integer
For i = 0 To strPackages.Length - 1
lstPackages.Items.Add(strPackages(i))
Next
End Sub
After I tried to select a value on lstPackages, but I just was not too sure if I was using the right code to select the item and return it to the main form:
Function CalcPackage()
Dim decPackages As Decimal = 0D
If lstPackages.SelectedIndex = -1 Then
MessageBox.Show("Select a package")
Else
For i = 0 To lstPackages.SelectedItem - 1
decPackages = lstPackages.SelectedItem(i)
Next i
End If
Return decPackages
End Function
When I have selected the item in the lstPackages, I tried to send the selected item back to the main form, but ran into a problem here:
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnClose.Click
Dim frmMainForm As New MainForm
Dim decTotal As Decimal
decTotal = CalcPackage()
'I was stuck in this part and wasn't sure how to return it to lblTotalPrice (and also close the second form too)
frmMainForm.lblTotalPrice.Text = decTotal.ToString("c")
frmMainForm.Show()
Me.Close()
End Sub
So yea sorry if my code is weird, but I'm hoping to get help on how to return the value of the item to lblTotalPrice on the main form, thanks guys

Part of your problem is that you are newing up an instance of the main form in the button exit click event handler of the second form, as shown in this code posted:
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnClose.Click
Dim frmMainForm As New MainForm
Dim decTotal As Decimal
decTotal = CalcPackage()
'I was stuck in this part and wasn't sure how to return it to lblTotalPrice (and also close the second form too)
frmMainForm.lblTotalPrice.Text = decTotal.ToString("c")
frmMainForm.Show()
Me.Close()
End Sub
Instead pass an instance of the main form to the second form via its constructor, like this:
Public Class SecondForm Inherits Form
Dim theMainForm As MainForm
Public Sub New(mainForm As MainForm)
theMainForm = mainForm
End Sub
End Class
Now you can reference the lblTotalPrice in the MainForm class via the theMainForm variable, like this:
theMainForm.lblTotalPrice.Text = lstPackages.SelectedItem
The theMainForm.lblTotalPrice.Text should only be updated in response to an item being selected from lstPackages not when the second form is closed; so handle the updating of the main form's label in the SelectedIndexChanged event of lstPackages, like this:
Protected Sub lstPackages_IndexChanged(sender As Object, e As EventArgs)
Dim decTotal As Decimal
decTotal = CalcPackage()
theMainForm.lblTotalPrice.Text = decTotal.ToString("c")
End Sub
All the exit button click event handler should do is to show the main form and close the second form, like this:
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnClose.Click
theMainForm.Show()
Me.Close()
End Sub

Just display SecondForm with ShowDialog(), then retrieve the value with the reference to it that you already have:
Public Class MainForm
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim sf As New SecondForm
If sf.ShowDialog = Windows.Forms.DialogResult.OK Then
lblTotalPrice.Text = sf.TotalPrice
End If
End Sub
End Class
Over in SecondForm:
Public Class SecondForm
Private _TotalPrice As Decimal
Public ReadOnly Property TotalPrice As Decimal
Get
Return _TotalPrice
End Get
End Property
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnClose.Click
If lstPackages.SelectedIndex = -1 Then
MessageBox.Show("Select a package")
Else
_TotalPrice = lstPackages.SelectedItem(0)
Me.DialogResult = Windows.Forms.DialogResult.OK
End If
End Sub
End Class

Related

simple dialog like msgbox with custom buttons (vb)

I want to ask user for example "Do you want to go right or left?".
To have simple Code I use MSGBOX with a prompt like:
"Do you want to go right or left"
Press "YES for 'right' / NO for 'left'"
Then I process Yes/No/Cancel that was pressed. This works but is ugly and in some cases hard to understand.
Also in Addition in some cases I have more than 2 choices - but that is probable another question...
You can create one dynamically
Public Module CustomMessageBox
Private result As String
Public Function Show(options As IEnumerable(Of String), Optional message As String = "", Optional title As String = "") As String
result = "Cancel"
Dim myForm As New Form With {.Text = title}
Dim tlp As New TableLayoutPanel With {.ColumnCount = 1, .RowCount = 2}
Dim flp As New FlowLayoutPanel()
Dim l As New Label With {.Text = message}
myForm.Controls.Add(tlp)
tlp.Dock = DockStyle.Fill
tlp.Controls.Add(l)
l.Dock = DockStyle.Fill
tlp.Controls.Add(flp)
flp.Dock = DockStyle.Fill
For Each o In options
Dim b As New Button With {.Text = o}
flp.Controls.Add(b)
AddHandler b.Click,
Sub(sender As Object, e As EventArgs)
result = DirectCast(sender, Button).Text
myForm.Close()
End Sub
Next
myForm.FormBorderStyle = FormBorderStyle.FixedDialog
myForm.Height = 100
myForm.ShowDialog()
Return result
End Function
End Module
You see you have options as to what buttons are present, the message, and title.
Use it like this
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim result = CustomMessageBox.Show(
{"Right", "Left"},
"Do you want to go right or left?",
"Confirm Direction")
MessageBox.Show(result)
End Sub
End Class
In my example, the prompt is "Do you want to go right or left?" and the options are "Right" and "Left".
The string is returned as opposed to DialogResult because now your options are unlimited (!). Experiment with the size to your suiting.
You need to create your own "custom" msgbox form according to your needs, and its better to create a reusable control - pass your "question" string via the constructor of your custom control.
You need some "way" to get the user decision from out side your custom msgbox - one way is use DialogResult Enum for that.
Here is a basic example i just wrote to demonstrate that, please see the comments i have added inside the code.
create a new project with 2 forms, Form1 will be the main form that will call the custom msgbox and Form2 will be the custom msgbox:
Form1:
Form2:
Code for Form1:
Public Class Form1
Private Sub btnOpenCustomMsgbox_Click(sender As Object, e As EventArgs) Handles btnOpenCustomMsgbox.Click
Dim customMsgbox = New Form2("this is my custom msg, if you press yes i will do something if you press no i will do nothing")
If customMsgbox.ShowDialog() = DialogResult.Yes Then
' do something
MsgBox("I am doing some operation...")
Else
' do nothing (its DialogResult.no)
MsgBox("I am doing nothing...")
End If
End Sub
End Class
Code for Form2:
Public Class Form2
' field that will contain the messege
Private PromtMsg As String
Sub New(ByVal promtmsg As String)
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
' set global field with the argument that was passed to the constructor
Me.PromtMsg = promtmsg
End Sub
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' set the msg label
Me.lblPromtMsg.Text = Me.PromtMsg
End Sub
Private Sub btnCustomYes_Click(sender As Object, e As EventArgs) Handles btnCustomYes.Click
' user choosed yes - return DialogResult.Yes
Me.DialogResult = DialogResult.Yes
Me.Close()
End Sub
Private Sub btnCustomNo_Click(sender As Object, e As EventArgs) Handles btnCustomNo.Click
' user choosed no - DialogResult.no
Me.DialogResult = DialogResult.No
Me.Close()
End Sub
End Class
it can be much more sophisticated but if you explore that example i hope you will understand the general idea.

Custom Textbox Zoom - Return text to active datagridview cell?

I have 2 Datagridview controls in same form. Each Datagrid has some columns where user will write long texts, so I designed form with RichTextBox that opens when user double-clicks these columns to enlarge text-entry. Code works, but I want to use same form for both Datagrids, so I should somehow return text to active datagridview cell. Here is my code (for Datagridview1):
TextZoomForm:
Public Class TextZoomForm
Public OpenedForm1 As New Form1
Private Sub RichTextBox1_DoubleClick(sender As Object, e As EventArgs) Handles RichTextBox1.DoubleClick
OpenedForm1.DataGridView1.CurrentCell.Value = RichTextBox1.Text
OpenedForm1.Label24.Focus()
Me.Close()
End Sub
Private Sub TextZoom_Load(sender As Object, e As EventArgs) Handles Me.Load
RichTextBox1.Text = OpenedForm1.DataGridView1.CurrentCell.Value
End Sub
End Class
DataGridView1_CellMouseDoubleClick in Form1:
Private Sub DataGridView1_CellMouseDoubleClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseDoubleClick
If e.ColumnIndex = 1 Then
Dim cp = Cursor.Position
cp.Y += CInt(Cursor.Size.Height * (-0.5))
cp.X += CInt(Cursor.Size.Width * 0.8)
Dim f As New TextZoomForm()
f.OpenedForm1 = Me
f.Show()
f.Location = New Point(cp)
End If
End Sub
Any ideas on how to return text to active datagridview cell?
Change your zoomed form so that it doesn't know where its data comes from. Instead the control using it will pass the data.
Public Class TextZoomForm
Public Property ZoomedText As String
Get
Return RichTextBox1.Text
End Get
Set(value As String)
RichTextBox1.Text = value
End Set
End Property
Private Sub RichTextBox1_DoubleClick(sender As Object, e As EventArgs) Handles RichTextBox1.DoubleClick
Me.Close()
End Sub
End Class
To call the form change your code to the following:
Private Sub DataGridView1_CellMouseDoubleClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseDoubleClick
...
Dim f As New TextZoomForm()
f.ZoomedText = DataGridView1.CurrentCell.Value
f.ShowDialog()
'Great breakpoint location.
DataGridView1.CurrentCell.Value = f.ZoomedText
Label24.Focus()
....
End Sub
Using ShowDialog prevents the user from changing the current cell part way through your call.
If you need it modeless then you should:
store the cell that the user has selected
handle the FormClosing event.
Test the DialogResult to make sure the user pressed ok
write the data back to the stored cell.

vb.net returning string as dialog result

I'm creating an AddIn for Autodesk Inventor, the AddIn is a simple button in the ribbon.
When the user presses the button a new form is created as dialog.
Private Sub ButtonClick()
Dim oWindow As New CopyDesignForm(string1, string2)
oWindow.ShowDialog()
End Sub
The user will then do some operations and a file path as string is the result of his actions. I would now like to return this value so my AddIn can process the file.
But I can't seem to find a good example of this. I can only find an excellent sample of how to pass the ok or cancel result. But not how to get to a variable of the dialog.
Link to ok and cancel result sample
You can add a string property to the dialog and set the value of the property in your dialog,Then after showing the dialog, check if the dialog result was OK, then read the property.
Code for your customm dialog:
Public Class MyCustomDialog
Public Property SomeProperty As String
Private Sub OKCommandButton_Click(sender As Object, e As EventArgs) _
Handles OKCommandButton.Click
Me.SomeProperty = "Some Value"
Me.DialogResult = Windows.Forms.DialogResult.OK
End Sub
Private Sub CancelCommandButton_Click(sender As Object, e As EventArgs) _
Handles CancelCommandButton.Click
Me.SomeProperty = Nothing
Me.DialogResult = Windows.Forms.DialogResult.Cancel
End Sub
End Class
Code for your usage of custom dialog:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim f As New MyCustomDialog
If (f.ShowDialog() = DialogResult.OK) Then
MessageBox.Show(f.SomeProperty)
End If
End Sub
End Class

VB.NET: Passing variable between forms, error

I want to pass the value of an exact variable to another form...
To be more precise I'm building a game in which a player answer a few questions so I want to pass the variable that contains the correct answer to another form which works as the end game window and displays the score... I'm using this kind of code in the end game window:
Public Class Form2
Public Property CCount As Integer
Private Sub Form5_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Label1.Text = CCcount
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
CCount = 0
Form1.Show()
Me.Close()
End Sub
End class
And this in the main form:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Lines of code
Form2.CCount +=1
'Lines of code
'Me.Hide()
'Form2.Show()
EndSub
The first time that I'm "playing the game" everything works fine, but if try to replay it the displaying scores never changes... It remains the same as the first run..
Any ideas how I can fix this out?
You assign value of CCount to the Label only ones when form was loaded.
Load event raised only one time.
Put label updating code inside CCount Property Setter
Private _CCount As Integer
Public Property CCount As Integer
Get
Return _CCount
End Get
Set (value As Integer)
If _CCount = value Then Exit Property
_CCount = value
Me.Label1.Text = _CCount.ToString()
End Set
End Property

Copying text from one textbox to one on another form and sorting between textboxes

I am still learning on vb.net but I have main form (form1) that has 2 columns. One called Red and the other Yellow. I have a button that opens a form (form2) that has a textbox that allows the user to put in someone's name and a combobox to select a color. What I am trying to accomplish it when they click the submit button on form2, the name will show up in the proper column in form1. Both colors on form1 has their own textbox under it. Red has textbox1 and Yellow has textbox2. Can anyone assist on how I would go about doing this? I am using Visual Studio 2010 VB.Net. Thanks!!
Danny
So many ways to do this...here's another one.
Code in Form1:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim f2 As New Form2
If f2.ShowDialog = Windows.Forms.DialogResult.OK Then
Select Case f2.ComboBox1.SelectedItem.ToString.ToLower
Case "red"
TextBox1.AppendText(f2.TextBox1.Text & Environment.NewLine)
Case "yellow"
TextBox2.AppendText(f2.TextBox1.Text & Environment.NewLine)
Case Else
MessageBox.Show("Unkown Color!")
End Select
End If
End Sub
End Class
and in Form2:
Public Class Form2
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.DialogResult = Windows.Forms.DialogResult.Cancel
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If TextBox1.TextLength > 0 AndAlso ComboBox1.SelectedIndex <> -1 Then
Me.DialogResult = Windows.Forms.DialogResult.OK
End If
End Sub
End Class
From a simple workflow perspective, you can have Form 2 call a method on Form 1 and provides the new name and color. Form 1 would then add the name to the correct column. There are a number of ways to handle this- one would be to have Form 1 instantiate form 2 then pass in a delegate reference for the method that will take the name and color.
So in Form 1 -
Public Sub HandleAdd(name as String, color as String)
' Do Stuff Here.
End Sub
Public Sub AddPlayerButton_Click(sender as Object, e as EventArgs) Handles AddPlayerButton.Click
Dim frm As New Form2
frm.AfterAdd = AddressOf HandleAdd
frm.Show
End Sub
And in Form 2 -
Public Property AfterAdd As Action(of String, String)
Public Sub OKButton_Click(sender as Object, e as EventArgs) Handles OK.Click
If AfterAdd IsNot Nothing Then AfterAdd(playerName.value, playerColor.value)
End Sub
Or something like that.