update value of a variable outside a class in VB.NET - vb.net

I have a class derived from a Form, it has textbox for username and password and an OK button. I want it to behave like an InputBox so I can use it like this:
Dim Username As String = ""
Dim Password As String = ""
Dim authorization As New Authorization(Username, Password)
authorization.ShowDialog()
'The user will click OK and I will expect the Username and Password to change based on the user input
MsgBox(Username & " " & Password)
The Authorization class:
Public Class Authorization
Dim RefUsername As String
Dim RefPassword As String
Public Sub New(ByRef Username As String, ByRef Password As String)
InitializeComponent()
RefUsername = Username 'I'm trying to pass reference instead of value
RefPassword = Password 'I'm trying to pass reference instead of value
End Sub
Private Sub OKButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AuthorizeButton.Click
RefUsername = Username.Text 'I'm trying to change value of variable outside the class
RefPassword = Password.Text 'I'm trying to change value of variable outside the class
Me.Close()
End Sub
End Class
In short, I want to change the value of variables outside the class when the user clicks the OK, how am I going to accomplish that?

You can just add properties to the class to modify it from outside like any other class:
Public Class Authorization
Friend Property RefUsername As String
Friend Property RefPassword As String
'this constructor isn't really necessary with this new approach,
'but I'll leave it as-is.
Public Sub New(ByRef Username As String, ByRef Password As String)
InitializeComponent()
RefUsername = Username '
RefPassword = Password
End Sub
Private Sub OKButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles AuthorizeButton.Click
Me.DialogResult = DialogResult.OK
End Sub
End Class
From the outside you then get username and password:
Dim Username As String = ""
Dim Password As String = ""
Dim authorization As New Authorization(Username, Password)
'this constructor isn't really necessary with this new approach,
'but I'll leave it as-is.
If authorization.ShowDialog() = DialogResult.OK Then
MsgBox(authorization.RefUsername & " " & authorization.RefPassword)
End If

Public Class Authorization
Dim RefUsername As String
Dim RefPassword As String
Public Sub New(ByRef Username As String, ByRef Password As String)
InitializeComponent()
RefUsername = Username 'I'm trying to pass reference instead of value
RefPassword = Password 'I'm trying to pass reference instead of value
End Sub
Private Shared Function PromptUser() As ReturnClass
Dim currentReturnClass as ReturnClass
// Dialog Goes Here
currentReturnClass.UserName = Username.Text
currentReturnClass.Password = Password.Text
Me.Close()
End Sub
End Class
private class ReturnClass
Dim userName as String
Dim password as String
Dim userAcceptedDialog as Boolean
' Setters and Getters
End Class
Your calling code:
Dim Username As String = "Default User"
Dim Password As String = "Default Password"
Dim authorization As New Authorization(Username, Password)
Dim myReturnClass as ReturnClass
myReturnClass = authorization.PromptUser()
MsgBox(myReturnClass.Username & " " & myReturnClass.Password)

Related

Login Form - Not working

Struggling with creating a login from a text file database. The information needs to be manually entered into the text file before it works... see my code below for the form. Its not letting me login.
Public Class UserLogin
Private PWD As String
Public User As User
Public Users As List(Of User) = New List(Of User)
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Me.Close()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
If isValidData() Then
If isValidUser() Then
MessageBox.Show("Login Successful")
Form2.Show()
Me.Hide()
Else
MessageBox.Show("Incorrect Username or password")
End If
End If
Catch ex As Exception
MessageBox.Show(ex.Message & vbCrLf & vbCrLf & ex.GetType.ToString & vbCrLf & vbCrLf & ex.StackTrace, "User Does not Exist")
End Try
End Sub
Private Function isValidData() As Boolean
Return Validator.IsPresent(TextBox1, "Username") AndAlso
Validator.IsPresent(TextBox2, "Password")
End Function
Private Function isValidUser() As Boolean
Return UserDB.ValidateUser("Username", "Password")
End Function
Public Sub setPath(cwd As String)
PWD = cwd
End Sub
End Class
User class below :
Public Class User
Public Sub New()
End Sub
Public Sub New(Username As String, Password As String)
Me.Username = Username
Me.Password = Password
End Sub
Public Property Username As String
Public Property Password As String
Public Function GetDisplayText(sep As String) As String
Dim text As String = Username & sep & Password
Return text
End Function
End Class
UserDB class Below
Imports System.IO
Public Class UserDB
Private Const Databasename = "C:\Depreciate\Users.txt"
Public User As New User
Public Shared Users As List(Of User) = New List(Of User)
Public Shared Function GetUsers(Dir As String) As List(Of User)
Dim Users As New List(Of User)
Dim textIn As New StreamReader(
New FileStream(Databasename, FileMode.OpenOrCreate, FileAccess.Read))
Do While textIn.Peek <> -1
Dim row As String = textIn.ReadLine
Dim columns As String() = row.Split(CChar(","))
Dim User As New User
User.Username = columns(0)
User.Password = columns(1)
Users.Add(User)
Loop
textIn.Close()
Return Users
End Function
Public Shared Function ValidateUser(username As String, password As String) As Boolean
Dim Validated = False
For Each userEntry As User In Users
If username = userEntry.Username AndAlso password = userEntry.Password Then
Validated = True
Exit For
End If
Next
Return Validated
End Function
End Class
looks like you compare all user names and passwords to the strings "Username" and "Password" by calling:
Return UserDB.ValidateUser("Username", "Password")
in isValidUser.Probably you should better pass the actual username and the password which the user has typed instead?
There are a couple of problems in your code:
First I can't see anywhere the call to UserDB.GetUsers that should initialize the list of users from the file. But also assuming that you have made the call in some other place, there is another problem in that method.
This line inside the GetUsers method creates a new variable of type List(Of User) and name it with the same name of the Shared one effectively hiding the one declared at the global class level
Dim Users As New List(Of User)
Then your code continue and fills a variable named Users but this variable is not the shared one declared at the class global level. Of course, when you search your username and password in the shared variable you don't find anything.
Just remove that line and let the call To GetUsers fill the same variable used in the check
(Of course I also assume that when you call UserDB.ValidateUser you will pass an actual Username and a password and not the placeholders string that you are using in the code above)

VB.NET - Cannot bind to the new display member

I'm trying to assign the DataSource for a ComboBox that will allow the user to select a member. I'm receiving this error when run my application:
Cannot bind to the new display member.
Parameter name: newDisplayMember.
Here's my code:
Private Sub StartScreen_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'GetAllELData()
ddlMember.DataSource = GetMemberList()
ddlMember.DisplayMember = "DisplayName"
ddlMember.ValueMember = "ID"
End Sub
Private Function GetMemberList() As List(Of Member)
Dim rval = New List(Of Member)
Dim dv As DataView = New DataView
Dim myConnString = ConfigurationSettings.AppSettings("ConnString")
Try
dv = SqlHelper.ExecuteDataset(myConnString, CommandType.StoredProcedure, "spGetData").Tables(0).DefaultView
Catch ex As Exception
MessageBox.Show(ex.Message, "Database Error", MessageBoxButtons.OK)
End Try
For Each row As DataRowView In dv
Dim mbrNum As String = row.Item("IMMBR_CD").ToString()
Dim mbrName As String = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(row.Item("IMMBR_NM20").ToLower())
Dim mbrState As String = row.Item("IMMBR_ST").ToString()
'assigns the member data to the list of members
rval.Add(New Member(mbrNum, mbrName, mbrState))
Next
Return rval
End Function
And then my class definition:
Public Class Member
Public ID As String
Public Name As String
Public State As String
Public DisplayName As String
Public Sub New(ByVal i As String, ByVal n As String, ByVal s As String)
ID = i
Name = n
State = s
DisplayName = ID & " - " & Name & ", " & State
End Sub
Public Overrides Function ToString() As String
Dim rval As String = ID & " - " & Name & ", " & State
Return rval
End Function
Public Function GetID() As String
Return ID
End Function
Public Function GetName() As String
Return Name
End Function
Public Function GetState() As String
Return State
End Function
End Class
I don't know why I'm getting the error. The application correctly loads the member as intended and works just fine once I click "Continue" on the error popup. Everything I've found about the error is for people passing a table as their DataSource instead of a custom class like me and the answers contain only code snippets rather than an explanation of the why there's a problem.
Can anyone help me figure out what's wrong here?
Thanks a bunch!
The errors were caused by binding directly to the fields. Defining those as properties and binding to the properties solved the issue.
Public ReadOnly Property GetID() As String
Get
Return Me.ID
End Get
End Property
Public ReadOnly Property GetName() As String
Get
Return Me.Name
End Get
End Property
Public ReadOnly Property GetState() As String
Get
Return Me.State
End Get
End Property
Public ReadOnly Property GetDisplayName() As String
Get
Return Me.DisplayName
End Get
End Property
And:
Private Sub StartScreen_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'GetAllELData()
ddlMember.DataSource = GetMemberList()
ddlMember.DisplayMember = "GetDisplayName"
ddlMember.ValueMember = "GetID"
End Sub

Why does my new form keep moving to the back?

Visual Basic .NET using Visual Studio 2013
I have a form that I open from another form, but when I do, it always goes behind the form that opened it. Al code that passes to the new form, gets passed before the form.Show().
Here is the code that opens the new form.
Private Sub OpenContentWindow(strNewNavigation As String)
Dim newContent As New FContent
newContent.SetIETMPath(strIETMPath)
newContent.SetIETMName(strIETMName)
newContent.SetIETMMan(strNewNavigation)
newContent.SetIETMIcon(strIETMIcon)
newContent.SetPageToLaunch(strNewNavigation)
newContent.Show()
End Sub
Here is the code from the new form.
Public Class FContent
#Region "Variables/Class Instances"
Private logger As New CDataLogger
Private pathing As New CPaths
Private annotes As New CAnnotes
Private mouser As New CMouse
Private strIETMPath As String
Private strIETMName As String
Private strIETMMan As String
Private strIETMIcon As String
Private strPageToLaunch As String
#End Region
#Region "Load Sub Routines"
' Form Load
Private Sub FContent_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Text = strIETMName
Me.Icon = New System.Drawing.Icon(strIETMIcon)
StartNavigation(strPageToLaunch)
End Sub
' Just pass in the file you want to view
Public Sub StartNavigation(strFileToNavigate As String)
StartNavigation(strFileToNavigate, True)
End Sub
' Just pass in the file you want to view ( if a manual change it will load TOCs also )
Public Sub StartNavigation(strFileToNavigate As String, blnManual As Boolean)
If blnManual Then
wbContent.Navigate(New Uri(strIETMPath & strFileToNavigate))
wbTOC.Navigate(New Uri(strIETMPath & strIETMMan & "\toc.html"))
wbLOF.Navigate(New Uri(strIETMPath & strIETMMan & "\lof.html"))
wbLOT.Navigate(New Uri(strIETMPath & strIETMMan & "\lot.html"))
wbLOC.Navigate(New Uri(strIETMPath & strIETMMan & "\loc.html"))
Else
wbContent.Navigate(New Uri(strIETMPath & strFileToNavigate))
End If
End Sub
#End Region
#Region "Set Sub Routines"
' Set IETM Path
Public Sub SetIETMPath(strNewIETM As String)
strIETMPath = strNewIETM
End Sub
' Set IETM Name
Public Sub SetIETMName(strNewIETM As String)
strIETMName = strNewIETM
End Sub
' Set IETM Manual
Public Sub SetIETMMan(strNewIETM As String)
strIETMMan = strNewIETM.Substring(0, strNewIETM.IndexOf("/"))
End Sub
' Set IETM Icon
Public Sub SetIETMIcon(strNewIETM As String)
strIETMIcon = strNewIETM
End Sub
' Set Page To Launch
Public Sub SetPageToLaunch(strNewPage As String)
strPageToLaunch = strNewPage
End Sub
#End Region
The easiest way to ensure the display above the calling form is to set the Owner property of the called form to the instance of the calling form.
So, supposing that this OpenContentWindow method is inside the class code of the form that want to create the instance of an FContent you could call the Show method passing the reference to the current form instance
Private Sub OpenContentWindow(strNewNavigation As String)
Dim newContent As New FContent
newContent.SetIETMPath(strIETMPath)
newContent.SetIETMName(strIETMName)
newContent.SetIETMMan(strNewNavigation)
newContent.SetIETMIcon(strIETMIcon)
newContent.SetPageToLaunch(strNewNavigation)
newContent.Show(Me)
End Sub
In the link above (MSDN) you could read
When a form is owned by another form, it is closed or hidden with the
owner form. For example, consider a form named Form2 that is owned by
a form named Form1. If Form1 is closed or minimized, Form2 is also
closed or hidden. Owned forms are also never displayed behind their
owner form. You can use owned forms for windows such as find and
replace windows, which should not disappear when the owner form is
selected. To determine the forms that are owned by a parent form, use
the OwnedForms property.
Did you try "newContent.BringToFront()" after newContent.Show () or newContent.TopMost =true ?

Retrieve a object from a list of objects in visual basic and use it to fill text/combo boxes

I have a class as seen below:
Public Class parameters
Public Property test As String
Public Property test_type As String
Public Property user_test_name As String
Public Property meas As String
Public Property spec As String
...etc
End Class
I make a list of objects that I import from a csv somewhere. The user_test_name's from the list gets sent to a list box:
For Each parameters In param
' MsgBox(parameters.user_test_name)
ListBox1.Items.Add(parameters.user_test_name)
Next
now when the user selects something from the list i want the rest of the properties of that particular user_test_name object to populate in certain text/combo boxes in the application. Here is how I grab what is selected.
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
Dim selected_name As String = ListBox1.SelectedItem()
' MsgBox(selected_name)
find_object_by_user_test_name(selected_name)
End Sub
Now i'm having difficulty finding the object with the selected_name from the list and using its properties to fill the text.combo boxes. I tried the following to no success:
Public Sub find_object_by_user_test_name(ByVal description)
MsgBox(description)
Dim matches = From parameters In param
Where parameters.user_test_name = description
Select parameters
' MsgBox(matches)
' MsgBox(matches.user_test_name)
TextBox1.Text = matches.test
TextBox2.Text = matches.test_name
etc,,, on and on
' populate_area(matches)
End Sub
Instead of adding the name (a string) to the ListBox, add your actual INSTANCE to it.
First, override ToString() in your class so that it displays properly in your ListBox:
Public Class parameters
Public Property test As String
Public Property test_type As String
Public Property user_test_name As String
Public Property meas As String
Public Property spec As String
Public Overrides Function ToString() As String
Return user_test_name
End Function
End Class
Next, add each instance to the ListBox:
For Each parameters In param
ListBox1.Items.Add(parameters)
Next
Now, the SelectedIndexChanged() event, you can cast the SelectedItem() item back to parameters and you already have everything at your disposal:
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
If ListBox1.SelectedIndex <> -1 Then
Dim P As parameters = DirectCast(ListBox1.SelectedItem, parameters)
' ... do something with "P" ...
Debug.Print(P.user_test_name & " --> " & P.test)
End If
End Sub
If the user_test_names are unique, it may be easier to use a dictionary and retrieve the objects that way.
Dim params As New Dictionary(Of String, parameters)
params.add(MyParameterObject.user_test_name, MyParameterObject)
Then
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
Dim selected_name As String = ListBox1.SelectedItem()
Dim selected_param as parameters = params(selected_name)
End Sub
Something like this should do it:
Public Sub find_object_by_user_test_name(ByVal description As String)
' assuming param is your list of parameter objects
For Each p In param
If p.user_test_name = description Then
TextBox1.Text = p.test
TestBox2.Text = p.test_name
...
Exit For
End If
Next
End Sub
A few notes about your code. First, you can't allow two objects to have the same user_test_name. Second, you can't use parameters as a variable name if you already have a class called parameters in your current namespace (which you do).
There is a simpler solution than any of these--just do the following:
Dim i as Integer = ListBox1.SelectedIndex
Then you can use i as an index to your original list of objects.

Reading radio buttons from module in VB.net

i have created this module and i know that the student and teacher in the structure student and teacher are put as string (these are stored as my radio buttons), but when i save these to the file, this works by saving a true or false value for the id and password. however, i am unable to read the radio buttons from another class.
this is my module class
Imports System.IO
Module user_info_mod
Structure user
<VBFixedString(3)> Dim name As String
<VBFixedString(3)> Dim password As String
<VBFixedString(7)> Dim student As String
<VBFixedString(3)> Dim teacher As String
End Structure
Public newuser As user
Public userNumber As Integer = FreeFile()
Public userrecordNumber As Integer = 1
Public Sub setRecordNumber()
Dim n As Byte = 0
FileOpen(userNumber, "D:\users.dat", OpenMode.Random, OpenAccess.Read)
While Not EOF(userNumber)
n = n + 1 'increments the record number of the user
FileGet(userNumber, newuser, n)
End While
userrecordNumber = n
FileClose(userNumber)
End Sub
End Module
this is where i am trying to read the radio button in the main file ( newuser.student=True)
Private Sub cmdLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdLogin.Click
Dim password As String
password = txtPassword.Text
Dim username As String
username = txtUsername.Text
FileOpen(userNumber, "D:\users.dat", OpenMode.Random, OpenAccess.Read)
FileGet(userNumber, newuser, userrecordNumber)
If password = newuser.password And username = newuser.name And newuser.student = True Then
MsgBox("ID Accepted")
Dim frmNew As New Student_selection
frmNew.ShowDialog()
FileClose(userNumber)
Else
FileClose(userNumber)
MsgBox("ID is not accepted")
End If
End Sub
if i am to change the string to boolean in the module, this is not enabling me to save a user's file when setting the record number within the module, so what is the correct way in order to solve this problem?
problem has been solved. The order of the radio buttons within the module had to be changed first, and then changed to a Boolean. Dim student As Boolean