Using password character "*" in InputBox - vb.net

I want to use * character in inputbox but an error prompts
conversion from "*" to string invalid
How can I make my inputbox hide typed text into password characters?
Here is my code
Dim value As String
value = InputBox("Security Check", " Enter password", "*")
If value = "123456" Then
numr.Enabled = True
End If
End Sub

This is not possible with the built in Function InputBox. Ths value you are setting "*" is the defaultvalue of that function. http://msdn.microsoft.com/en-us/library/6z0ak68w(v=vs.90).aspx
Here is something you could do. http://www.vbforums.com/showthread.php?627996-Accepting-password-characters-for-InputBox-function

You have to define it yourself this is the Code I wrote to make a custom Password Input Box I defined it as a class and then inherited the form class and gave it custom properties By doing this I have created a property that determines if access is granted or not. you can create encryption and communicate with Database for password retrieval but this simply shows how to use the custom control.
Public Class Form1
Dim test As New CustomForm("workflow")
Public Class CustomForm
Inherits Form
Property SecretPassword As String
Property GrantAccess As Boolean
Sub New(Password As String)
GrantAccess = False
Me.SecretPassword = Password
Dim lbl As New Label
lbl.Text = "Password"
Me.Controls.Add(lbl)
Me.Text = "***PASSWORD INPUT REQUIRED***"
Dim frmSZ As New Size(400, 100)
Me.Size = frmSZ
Dim IBox As New TextBox
AddHandler IBox.KeyDown, AddressOf TextBox1_KeyDown
Dim ibox20 As New Point(100, 0)
IBox.Location = ibox20
IBox.PasswordChar = "*"
Me.Controls.Add(IBox)
Me.Show()
End Sub
Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs)
If e.KeyCode = Keys.KeyCode.Enter Then
Try
Dim passswordInput As String = sender.text
If passswordInput = Me.SecretPassword Then
GrantAccess = True
Me.Dispose()
Else
MsgBox("Sorry the password you entered is not correct please try again. The password is case sensitive make sure your caps lock is not on.")
End If
Catch ex As Exception
End Try
End If
End Sub
End Class
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MsgBox(test.GrantAccess)
End Sub
End Class

Unfortunately, the InputBox function doesn't have this parameter. VB.Net is reading your "*" as the value for the DefaultResponse parameter, or what value will equal if the user just accepts the default entry.
As a matter of fact, InputBox, while still found in the VisualBasic Namespace, is not considered up to date coding practice since 2003, but is still used by many who are or were accustomed to VB6 (including myself). It's most recent entry in the MSDN Visual Basic Reference is for the 2008 version of Visual Studio, and is not found in the current (2017) Visual Basic Language Reference.
The standard way of using an * or other password character in .Net, is to use a Windows Forms TextBox, and then use either the PasswordChar or UseSystemPasswordChar properties to change the nature of the TextBox inside the Form. These can be accessed in the in the Form Design Properties window, or as properties of the TextBox within your code.

Related

how do you pass the value/string of textbox to a XtraLabel in XtraReport in vb.net?

I want to pass a value or string from a textbox to the XtraLabel, what i did so far is create a parameter then send the value directly into the parameter then Data Bind the labels with my created parameters.
my code is this:
Imports DevExpress.XtraPrinting
Imports DevExpress.XtraReports.UI
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim reports As New XtraReport1()
Dim pt As New ReportPrintTool(reports)
reports.GetValue.Value = Integer.Parse(TextBox1.Text)
pt.AutoShowParametersPanel = True
pt.ShowPreviewDialog()
End Sub
End Class
it does pass the value however i have to click submit from parameters panel to pass the value or string to my GetValue Parameter which isn't what i want, and when i set pt.AutoShowParametersPanel = False it doesn't create any document at all. I want to enter a value from the textbox and when i click the button it will automatically load the value from textbox to the xtralabel in XtraReport1. Please help and also, is there another way to do this properly? as much as possible i want to use parameters but any kind of method will do. thank you.
Form1 picture:
XtraReport1 picture:
edit: i forgot to mention that this is a test program
Dim parameter As New Parameter() With {.Name = "GetValue", .Type = GetType(String), .Value = TextBox1.Text}
reports.Parameters.Add(parameter)
Create a Report Parameter
i read the devexpress website again to see how to use parameters, i almost failed to notice the "Tip" from the Web. What you need to do is:
reports.Parameters("GetValue").Value = TextBox1.Text
reports.RequestParameters = False
in that way the report won't ask for input and it will automatically send and submit input to the parameter/s

How to pass a form, object or data to a second form

I have created 2 forms.
The first one is the button that you want to back up.
In the second there are paths that can be modified.
How to make a reference that after pressing the "backup" button will get a path of 2 forms.
The path is saved when I closed form2
I know how to do it in one form but unfortunately I can not refer to another form.
Source of Form 2:
Private Sub Browser_from1_Click(sender As Object, e As EventArgs) Handles Browser_from1.Click
Dim FolderBrowserDialog1 As New FolderBrowserDialog
FolderBrowserDialog1.ShowDialog()
TextBox1from.Text = FolderBrowserDialog1.SelectedPath
If Browser_from1.Text <> "" And TextBox1from.Text <> "" Then
Backup.StartCopy.Enabled = True
End If
End Sub
Private Sub Browser_to1_Click(sender As Object, e As EventArgs) Handles Browser_to1.Click
Dim FolderBrowserDialog1 As New FolderBrowserDialog
FolderBrowserDialog1.ShowDialog()
TextBox2to.Text = FolderBrowserDialog1.SelectedPath
If Browser_to1.Text <> "" And TextBox2to.Text <> "" Then
Backup.StartCopy.Enabled = True
End If
End Sub
Private Sub TextBox1from_TextChanged(sender As Object, e As EventArgs) Handles TextBox1from.TextChanged
End Sub
Private Sub save_settings_Click(sender As Object, e As EventArgs) Handles save_settings.Click
My.Settings.pathmem = TextBox2to.Text
My.Settings.pathmem1 = TextBox1from.Text
My.Settings.Save()
End Sub
Private Sub setting_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1from.Text = My.Settings.pathmem1
TextBox2to.Text = My.Settings.pathmem
End Sub
End Class
You dont want to create a reference to a form - that would (or could) create a whole new form. You want to hold onto the form reference.
This is done by passing a reference to the forms, but the talk of one form fiddling with the controls on another form is a bad idea because it breaks encapsulation. But forms are classes (it says so at the top of each one), so you can add Properties and Methods (Sub and/or Functions) to facilitate passing information back and forth.
Method One - Passing a Form Reference
The simplest way is to pass whatever the other form needs in the constructor:
' form 1 / "main" form / form to return to
Dim frm As New Form6(Me)
frm.Show()
Me.Hide()
In order for this to work, you need to modify the constructor (Sub New) on the destination form:
Private frmReturnTo As Form
Public Sub New(f As Form)
' This call is required by the designer.
InitializeComponent()
frmReturnTo = f
End Sub
It is best not to create your own constructor until you are familiar with them. Use the drop downs at the top of the code window: from the left pick the form name; from the right, select New. The designer adds required code to them which must not be changed.
Do not add any code before the InitializeComponent() call at least until you are familiar with the life cycle of a form. The form and its controls do not exist until that runs.
To return to the "main" form:
If frmReturnTo IsNot Nothing Then
frmReturnTo.Show()
End If
You may want to remove some of the title bar buttons or add code to the form Closing event to handle when the user closes via the system menu or buttons.
Using the constructor is ideal for cases where there is some bit of data which the form must have in order to do its job.
Method Two - Passing Data
Thats all well and good, but what about passing data to another form? You can use the constructor for that too. In order to pass say, a string, integer and a Point:
' destination / second form:
Public Sub New(a As String, b As Int32, c As Point)
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
Label1.Text = a
Label2.Text = b.ToString
Label3.Text = c.ToString
End Sub
Call it like this:
' method two: pass data you want to share in the ctor
Dim frm As New frmData("hello", 6, New Point(150, 550))
frm.Show()
Result:
Method Three: Properties
Thats fine, but if there is a lots of data that way can get cumbersome. Plus, you may want to update some of the data from the calling/main form. For this you can create Properties on the form to handle the data:
Public Property Label1Text As String
Get
Return Me.Label1.Text
End Get
Set(value As String)
Me.Label1.Text = value
End Set
End Property
Rather than a private variable to act as the backing field, one of the controls is used. The name leaves a bit to be desired as it exposes implementation details. So, use names which describe what the data represents rather than where it displays.
Public Property SpecialValue As Integer
Get
Return Integer.Parse(Me.Label2.Text)
End Get
Set(value As Integer)
Me.Label2.Text = value.ToString
End Set
End Property
Public Property SomePoint As Point
Get
Dim data = Me.Label3.Text.Split(","c)
Return New Point(Convert.ToInt32(data(0)),
Convert.ToInt32(data(1))
)
End Get
Set(value As Point)
Me.Label3.Text = value.X.ToString & "," & value.Y.ToString
End Set
End Property
A point was used just to show that other data types can be used. Setting those values from the calling/original/source form:
Using frm As New Form6
frm.Label1Text = "Ziggy"
frm.SpecialValue = 42
frm.SomePoint = New Point(111, 222)
frm.ShowDialog()
' do stuff here with any changes
Dim theint = frm.SpecialValue
End Using ' dispose of dialog
The destination controls would well have been TextBoxes for the user to edit. The Property "wrappers" allow you to fetch those values back, so in this case, a Dialog was used.
Method Four: Methods
You can also use methods as a way to pass data to the second/helper form. Here a List(of T) collection will be passed. In the child/display form a method is added to receive the data which it then displays. The task represented is proofing or viewing a filtered list:
Public Sub UpdateDisplay(lst As List(Of SimpleItem), filter As String)
DataGridView1.DataSource = lst
Label1.Text = String.Format("{0} Total {1} Items", lst.Count, filter)
End Sub
In the main/calling form:
' form level variable
Private frmDV As frmDataView
elsewhere...perhaps in a Click event:
' myList is a simple list of items
' Users pick which color to filter on via a combo box
Dim filter As String
If cboListFilter.SelectedItem IsNot Nothing Then
'Dim frmDV As New frmDataView
If frmDV Is Nothing OrElse frmDV.IsDisposed Then
frmDV = New frmDataView
End If
filter = cboListFilter.SelectedItem.ToString()
' apply the filter
Dim tmpList = myList.Where(Function(w) w.Color = filter).ToList()
frmDV.UpdateDisplay(tmpList, filter)
frmDV.Show()
Else
Return
End If
Result:
With DataBased apps a modified version of this can allow for the case where you display DataGridView data in detail form on another form. You need not have the second form rung SQL to add or update the record, and then the main form running another query to "refresh" the display. If the DataSource is a DataTable backed up by a fully configured DataAdapter, pass the DataTable and have the child form add, change or delete using that. The data will automagically be in the DataTable and DataGridView`.
There are other ways to do this, but they generally all boil down to passing something from A to B. Which way is "best" depends on what the app does, the use-case and the nature of the data. There is no one right way or best way.
For instance, Properties and in many cases Functions allow the B Form to close the feedback loop. With DB items, a DataChanged property might tell the calling form that data was added or changed so that form knows to use the DataAdapter to update the db.
'SECOND FORM
Public class secondForm (blah blah)
Public overloads property owner as myMainForm
'Must be only the form you prepared for that
Private sub secondForm_load(blah blah) handles blah blah
Texbox1.text=Owner.customcontrol.text
End sub
End class
'MAIN FORM
public class myMainForm(blah blah)
Private sub button1_click(blah blah) handles blah blah
Dim NewSecondForm as secondForm = New secondForm
NewSecondForm.owner(me)
NewSecondForm.show(me)
NewSecondForm.dispose()
' so you can have bidirectional communication between the two forms and access all the controls and properties from each other
End sub
End Class

How To Evaluate a String Containing References to Windows Forms Controls At Runtime?

How can you, in VB.Net, evaluate the value of controls referenced in a string? Suppose you have a textbox N containing some alphanumeric content and it were referenced in a string variable like this:
Dim s As String = """Hello "" & N.Text & ""!"""
I'd like to be able to reevaluate the contents of the s variable elsewhere in the code (where there's no direct knowledge of the existence of N), for example, like this:
Dim e As String = Eval(s)
This isn't possible with VB.Net; no such Eval function is available. I've seen some nearly plausible solutions online such as using the old COM ScriptControl:
Private Shared _scriptControl As MSScriptControl.ScriptControl = New ScriptControl()
_scriptControl.Language = "VBScript"
Dim e As String = _scriptControl.Eval(s)
However, the reference to the N.Text property of a Windows Forms control is alien to the ScriptControl object, and therefore it throws an error.
Is there any other quick fix that won't require the purchase of a third-party component?
However, the reference to the N.Text property of a Windows Forms
control is alien to the ScriptControl object, and therefore it throws
an error. ... I only mentioned the ScriptControl idea to fend off
answers that might involve that approach I mentioned since I already
tried it and don't want to waste our time.
You can add the TextBox to the Script Control. First, get a reference to "N" using it's Name. Not sure if you've got the name of the control by itself already; if not, you may need to parse your string to get the name. Then use Controls.Find() to get a reference and pass that to AddObject(). Now your string can be evaluated as expected:
Private Shared _scriptControl As MSScriptControl.ScriptControl = New ScriptControl()
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
_scriptControl.Language = "VBScript"
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim ctlName As String = "N"
Dim ctl As Control = Me.Controls.Find(ctlName, True).FirstOrDefault
If Not IsNothing(ctl) Then
Try
_scriptControl.AddObject(ctlName, ctl)
Catch ex As Exception
End Try
Dim code As String = """Hello "" & N.Text & ""!"""
Dim result As String = _scriptControl.Eval(code)
MessageBox.Show(result)
End If
End Sub
String Interpolation was introduced in Visual Basic 14. Since the control is declared as a Friend variable in the Form's designer, then presumably you could use the reference to the control in the String like this:
Dim s As String = $"Hello {N.Text}!"

How do I pass a value from one TextBox to another TextBox in a different form?

Currently I have a TextBox on the first form called txtuserid and I want to pass the value of this to another TextBox called USERIDTextBox on a second form.
But when I try to run my code below, nothing gets passed to the TextBox on the second form. So I'm just wondering how I can pass this value from one form to another form?
Here is my code:
Private Sub cmdlogin_Click(sender As Object, e As EventArgs) Handles cmdlogin.Click
Try
If cn.State = ConnectionState.Open Then
cn.Close()
End If
cn.Open()
cmd.CommandText = "select userid,state from registration where userid= " & _
"'" & txtuserid.Text & "' and state='" & txtpw.Text & "'"
Dim dr As OleDb.OleDbDataReader
dr = cmd.ExecuteReader
If (dr.HasRows) Then
While dr.Read
' My Problem:
' This code shows the 2nd form but the USERIDTextBox value doesn't change?
Dim obj As New Sale
obj.USERIDTextBox.Text = txtuserid.Text
obj.Show()
End While
Else
MsgBox("Invalid username or PW")
End If
cn.Close()
Catch ex As Exception
End Try
End Sub
As a general rule, it's not a good idea to try accessing another object/forms controls directly. Instead, a better way to do it would be to pass the text in the 1st form's TextBox to a custom constructor on the 2nd form (the Sale one). Then the constructor on the 2nd form will be responsible for setting the value of the TextBox .
Here is an example of one way you could do this:
Sale.vb
Public Class Sale
Dim secondFormInputText As String
Public Sub New(inputTextFromFirstForm As String)
InitializeComponent()
' Set the class variable to whatever text string was passed to this form
secondFormInputText = inputTextFromFirstForm
End Sub
Private Sub Sale_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Set the textbox text using this class variable
USERIDTextBox.Text = secondFormInputText
End Sub
End Class
Login.vb
Private Sub cmdLoginExample_Click(sender As Object, e As EventArgs) Handles cmdLogin.Click
Dim obj As New Sale(txtuserid.Text)
obj.Show()
End Sub
So now instead of setting the Sale form's TextBox directly, you can pass the text on the 1st form to the constructor of the 2nd form. The constructor can then save the text it received to a class variable that the rest of the 2nd form can use.
One of the main benefits of this, is that if in the future you change your TextBox to a RichTextBox or possibly another control that might not even have a Text property, you won't have to go updating every single piece of code that tries to set the textbox value directly.
Instead you can change the TextBox to some other control, update the Sales form once with whatever changes you need to work with the new control, and none of the code on the other forms should need to be changed.
Edit:
Even though this question was specifically about how to pass a textbox value from one form to another form, you may also like to read the comments under your question. In particular, Plutonix had some very helpful advice on how you can improve your database code which might be of use to you.

How to pass a form as the parameter of a function vb.net

Currently in VB.NET I have two public subs like so:
Public Sub addmember1()
'Stuff
End Sub
Public Sub furtherinfo1()
'suff
End Sub
I haven't included the code where "'stuff" is as it is very long and is exactly the same in each sub, however the underlying the principle remains the same.
A certain sub is ran depending on a boolean value. like so...
If add_member = True Then
addmember1()
ElseIf add_member = False Then
furtherinfo1()
End If
How would I use one function to carry out the same procedure as above? (my current solution works but involves repeating the same section of code twice )
I tried the following however was unsuccessful
Public Function forms(ByVal frm As Windows.Forms.Form)
'stuff
End Function
and then run the function like so... (addmember and furtherinfo are the two forms I am working with)
If add_member = True Then
forms(addmember)
ElseIf add_member = False Then
forms(furtherinfo)
End If
here is the paste bin of all the code for context it's in modual and I want to use it for writing information to a word document. Lines 20-71, 76-128, 160-164 is what I am on about.
http://pastebin.com/xWD0RBuh
You can pass the form object to a Sub() in a module as below
Module Printing
Dim StrToAdd As String
Sub MySub(ByVal frm As Form)
'The first line is your code
StrToAdd = "Firstname: " & addmember.txtName.Text
'Change it to as below using frm.Controls("controlname").Text
StrToAdd = "Firstname: " & frm.Controls("txtName").Text
End Sub
End Module
After looking at your code at http://pastebin.com/xWD0RBuh it seems you have a global module with multiple sub routines. Each sub routine has references to controls (such as text boxes) on a form instance. This means each global module sub routine needs to have access to this form instance.
You have only copied in part of the application - the global module, but you have not copied in the form definition. I presume you have a form called addmember, but I don't see it in the example - aside from references in the global module.
Not sure how you use the sub routines - probably a click of a button. If it were me, I would create a class object with properties that hold the data to pass around - one property for each control on the form you want to print. On the click of the button, I would create an instance of the class and copy the values from the form controls into the class properties. I would then pass the instance of the class to the sub routines, and I would alter the sub routines to refer to an instance of the class instead of an instance of a form. That would provide a level abstraction between the form (UI) and the behavior (the sub routines that print). I may even go "crazy" and use an interface.
Does your code compile as-is?
The Problem is that your two Forms are two different classes. Even though you named your controls
the same, you can't just access them simply by frm.txtUsername.
What you could do is iterate through all controls of each form und find them by name:
Public Sub DoStuff(frm As Form)
Dim txtUsername As TextBox = GetControlByName(frm, "txtUsername")
txtUsername.Text = "Hello World"
End Sub
Private Function GetControlByName(container As Control, name As String) As Control
Dim retVal As Control = Nothing
If Not TryGetControlByName(container, name, retVal) Then Throw New ApplicationException("control not found")
Return retVal
End Function
Private Function TryGetControlByName(container As Control, name As String, ByRef ctl As Control) As Boolean
For Each item As Control In container.Controls
If item.Name = name Then
ctl = item
Return True
End If
'If item is a Container (like GroupBox, Panel) check its children
If TryGetControlByName(item, name, ctl) Then Return True
Next
Return False
End Function
If you want to get really fancy you could define a Class with the common Controls and fill them via a little
bit of reflection magic. Though this might be overkill:
Public Sub DoStuff2(frm As Form)
Dim wrapper As New CommonForm(frm)
wrapper.txtUsername.Text = "Hello Wolrd"
End Sub
Public Class CommonForm
Public Property txtUsername As TextBox
Public Property txtFoo As TextBox
Public Property txtBar As TextBox
'Add more Controls here...
Public Sub New(frm As Form)
For Each item In Me.GetType().GetProperties()
Dim value = GetControlByName(frm, item.Name)
item.SetValue(Me, value, Nothing)
Next
End Sub
Private Function GetControlByName(container As Control, name As String) As Control
Dim retVal As Control = Nothing
If Not TryGetControlByName(container, name, retVal) Then Throw New ApplicationException("control not found")
Return retVal
End Function
Private Function TryGetControlByName(container As Control, name As String, ByRef ctl As Control) As Boolean
For Each item As Control In container.Controls
If item.Name = name Then
ctl = item
Return True
End If
'If item is a Container (like GroupBox, Panel) check its children
If TryGetControlByName(item, name, ctl) Then Return True
Next
Return False
End Function
End Class