Donncha
Donncha

Reputation: 43

Passing Values from Form to Form

I need to pass a data bound integer that is from a populated list in a combo box from one for to another. In form 2 I need the rest of the fields to be populated based on that integer that is passed. I can pass the integer, however when form2 opens it keeps bringing up the value that is top of the list in my data base. All my textboxes and comboboxes are populated by drag and drop datasource.

studentNo is my global variable

Form1 code:

studentNo = cboStudents.SelectedText

Form2 code:

cboStudentNo.SelectedText = studentNo

Insted of .selectedText I have also tried .Text and .SelectedItembut to no avail.

Any suggestions would be greatly appreciated.

Upvotes: 1

Views: 88

Answers (1)

First off, if studentNo is an integer, then you should turn on Option Strict. This code wont compile:

studentNo = cboStudents.SelectedText

You are assigning text/string to an integer. Next, SelectedText probably doesnt do what you want; Intellisense tells us that it: Gets or sets the text that is selected in the editable portion of a ComboBox.. It is not the selected item in the list.

For a bound combobox of students, assuming the DisplayMember is the name and ValueMember is the ID, you want SelectedValue. You could get it in the SelectedValueChanged event:

' ToDo: check if selectedvalue is nothing to avoid NRE
studentNo = Convert.ToInt32(cbo.SelectedValue)

The conversion is necessary because the SelectedValue will be Object and you want to assign it to an integer. To pass that to the other form when it is needed, create a method to receive it:

' on form 2
Public Sub DisplayStudentInfo(id As Int32)
    ' wonderful things
End Sub

Then just pass the info. Assuming frm2 is an instance of Form2:

' push/pass/convey the desired ID to the other form:
frm2.DisplayStudentInfo(studentNo)

Alternatively, you could create a property on one form or the other as the means to expose it. This can be (too) passive: if Form1 exposes it as a prop, the other form(s) have no way to know when it changes. Using a method (Sub) allows you to add code to take action when a value is passed.

Upvotes: 1

Related Questions