create a message box on application start requiring users name then display it in the program? - vb.net

I would like a message box to pop-up at the start of the program asking what the customers name is. I then want this name to be displayed in a label that i have already created.
I went to application events and entered the code below after finding a few helpful tips around the internet. I get a message box allowing me to enter the customers name, so that bit works fine. The problem comes when I try to change the label. It says that 'label4' is not declared. I'm guessing that the application events section is a completely different section from the other forms.
If anyone could explain how I would go about doing this correctly and also explain the difference between so I can learn from this that would be great.
Dim message, title, defaultValue, myvalue As String
' Set prompt.
message = "Please Enter The Customers Name"
' Set title.
title = "New Customer"
' Set default value.
defaultValue = ""
' Display message, title, and default value.
myValue = InputBox(message, title, defaultValue)
label4.text = myvalue

The controls of a form a defined locally to that form, i.e. they are private members of that form and cannot be accessed from outside. Now it depends how your code is organized. If you are calling the InputBox before opening the main form then you need a way to pass the customer name to the main form. You can do that in the constructor the main form.
' In the main form
Public Sub New(ByVal customerName As String)
InitializeComponent() ' This call is required by the Windows Form Designer.
label4.Text = customerName
End Sub
Then you can create the main form like this (see also How to find the main() entry point in a VB.Net winforms app?)
Public Sub Main()
Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(False)
...
myValue = InputBox(message, title, defaultValue)
Dim frm As Form1 = New Form1(myValue)
' Starts the application.
Application.Run(frm)
End Sub

Related

VS 2022 project is missing the x64 option, only has Any CPU as option

I am at my wits end. I have a VS 2022 VB Winforms application that was working perfectly fine up until last night. Now I am getting numerous errors, most of which state "Value of type 'ComboBox()' cannot be converted to 'ComboBox()' because 'ComboBox' is not derived from 'ComboBox'". Another error staes "'DropDownWidth' is not a member of 'ComboBox'". The only thing I noticed is that the solution platform now reads "Any CPU" instead of "x64". I did not change any code that has to do with the combobox routines so the errors seemed to have come out of nowhere and the x64 solution platform is no longer an option. Any ideas? I included my code where the errors started popping up.
Public Class GlobalVar
Public Shared cmbBurgType() As ComboBox = {frmSearchNOC.cmbSearchBurgType, frmAddEntry.cmbAddBurgType}
Public Shared cmbSex() As ComboBox = {frmSearchNOC.cmbSearchSex, frmAddEntry.cmbAddSex}
Public Shared cmbRace() As ComboBox = {frmSearchNOC.cmbSearchRace, frmAddEntry.cmbAddRace}
Public Shared cmbPrefix() As ComboBox = {frmSearchNOC.cmbSearchHomeStreetPrefix, frmAddEntry.cmbAddHAddressPrefix}
Public Shared cmbSuffix() As ComboBox = {frmSearchNOC.cmbSearchHomeStreetSuffix, frmAddEntry.cmbAddHAddressSuffix}
Public Shared cmbState() As ComboBox = {frmSearchNOC.cmbSearchHomeState, frmAddEntry.cmbAddHAddressState}
Public Shared cmbPrecinct() As ComboBox = {frmSearchNOC.cmbSearchHomePrecinct, frmAddEntry.cmbAddHAddressPrecinct}
Public Shared cmbTattooLoc() As ComboBox = {frmSearchNOC.cmbSearchTattooLocation, frmAddEntry.cmbAddTattoo}
End Class
Public Sub LoadPresetDBDataCombobox(tableName As String, colName As String, objArray() As ComboBox)
Dim longestEntry As String = ""
Dim curText As String = ""
Dim sqliteReader As SQLiteDataReader
Dim sqliteReadCmd As SQLiteCommand
'clear combobox items
For Each curBox As ComboBox In objArray
curBox.Items.Clear()
Next
OpenDBConn() 'opens the database connection
sqliteReadCmd = GlobalVar.dbConn.CreateCommand()
sqliteReadCmd.CommandText = "Select " & colName & " FROM " & tableName
sqliteReader = sqliteReadCmd.ExecuteReader()
sqliteReadCmd.Dispose() 'disposes read command after it is used
'iterate through table
Using sqliteReader
While sqliteReader.Read
curText = sqliteReader.GetString(colName) 'gets the current table value for the selcted column
'places value into each combobox in array
For Each curBox As ComboBox In objArray
curBox.Items.Add(curText)
Next
'determines the length of the longest string to size to properly dize the drop down width to fit text
If (curText.Length > longestEntry.Length) Then
longestEntry = curText
End If
End While
'assigns the dropdownwidth based on an everage character width of 6 pixels
For Each curBox As ComboBox In objArray
curBox.DropDownWidth = ((longestEntry.Length * 7) + 10)
Next
sqliteReader.Close() 'close object
longestEntry = ""
End Using
CloseDBConn() 'closes the database connection
End Sub
Private Sub OpenChildForm(childForm As Form, formIndex As Integer)
If (currentChildForm IsNot Nothing) Then
currentChildForm.SendToBack()
End If
currentChildForm = childForm 'assigns passed in form as current form
childForm.TopLevel = False 'indicated the form is not top level because the main form is top level
childForm.Dock = DockStyle.Fill 'docks form to fill main form's panel
pnlMain.Controls.Add(childForm) 'adds form to the main panel on the main form
pnlMain.Tag = childForm 'associate form to main panel on main form
childForm.BringToFront() 'brings the related form to the front
childForm.Show()
Select Case formIndex
Case 0 'search noc form
'reloads various data from db into comboboxes in case items were added while on another tab
LoadPresetDBDataCombobox("BurgType", "typeName", GlobalVar.cmbBurgType) 'tattoo location
LoadPresetDBDataCombobox("Sex", "sexName", GlobalVar.cmbSex) 'sex
LoadPresetDBDataCombobox("Race", "raceName", GlobalVar.cmbRace) 'race
LoadPresetDBDataCombobox("StreetPrefix", "prefixName", GlobalVar.cmbPrefix) 'street prefix
LoadPresetDBDataCombobox("StreetSuffix", "suffixName", GlobalVar.cmbSuffix) 'street suffix
LoadPresetDBDataCombobox("State", "stateName", GlobalVar.cmbState) 'state
LoadPresetDBDataCombobox("Precinct", "precinctName", GlobalVar.cmbPrecinct) 'home precinct
LoadPresetDBDataCombobox("BodyPart", "bodyPartName", GlobalVar.cmbTattooLoc) 'tattoo location
Case 1 'browse results form
Case 2 'add entry form
'reloads various data from db into comboboxes in case items were added while on another tab
LoadPresetDBDataCombobox("BurgType", "typeName", GlobalVar.cmbBurgType) 'tattoo location
LoadPresetDBDataCombobox("Sex", "sexName", GlobalVar.cmbSex) 'sex
LoadPresetDBDataCombobox("Race", "raceName", GlobalVar.cmbRace) 'race
LoadPresetDBDataCombobox("StreetPrefix", "prefixName", GlobalVar.cmbPrefix) 'street prefix
LoadPresetDBDataCombobox("StreetSuffix", "suffixName", GlobalVar.cmbSuffix) 'street suffix
LoadPresetDBDataCombobox("State", "stateName", GlobalVar.cmbState) 'state
LoadPresetDBDataCombobox("Precinct", "precinctName", GlobalVar.cmbPrecinct) 'home precinct
LoadPresetDBDataCombobox("BodyPart", "bodyPartName", GlobalVar.cmbTattooLoc) 'tattoo location
Case 3'user settings form
Case 4 'administrator form
End Select
End Sub
Above, the errors come into play with all the GlobalVar parameters as well as the dropdownwidth call:
LoadPresetDBDataCombobox("StreetPrefix", "prefixName", GlobalVar.cmbPrefix)
curBox.DropDownWidth = ((longestEntry.Length * 7) + 10)
I tried updating VS 2022 and then reinstalled it. Neither of which worked, obviously, considering I'm asking this question. It's probably something simple and stupid but I am fried and could use some help.
Thanks to anyone who spent time reading my question. I have no idea how or when the following import got added to one of my routines but I commented it out and all the errors went away:
Imports System.Windows.Controls
I noticed it when I was copying code from my broken project to a new project to see when the errors start popping up. My best guess is that it was importing a combobox control that was different from the combobox I was trying to pass into the routine, but any comments that explain the reason are appreciated.

Access 2013 - Save Value from Textbox and display again when form is opened after close

I want to save a value from textbox in a string for example and display it again when the form get's openend.
I have two textboxes PriceRangeOne and PriceRangeTwo .. The user enter here for example 20 and 40
The problem i have is that when the user switches between Form and Report the values in this textboxes are beeing deleted. How can i save them?
I tried adding a sourcecontrol to the fields but had name errors eventhough i used different names.
I tried adding this to on change and retrieve it in an onload
Dim eingabe As String = textBox1.Text or .Value
Still didn't worked. Does anyone know a way to do this?
Typically, the most efficient and reliable way to do this is to have some form auto-open when the database is opened. It could be a dashboard, or just some form with nothing else on it. Whatever you use, launch it when the database opens and then minimize it. Now you have a form that's always open, as long as the application is open. Add a couple of textboxes to this form/dashboard.
When you close your form referenced in this question, write the values of PriceRangeOne and PriceRangeTwo to the textboxes on the form I described above. Then, when you open a new form or report, you can reference the values in those textboxes. Since the form is always open, you can reference these values at any time from any form or report until you close your database.
Solved it with variables.
I declared global variables in my standart module
For example
Public PriceOne As Double
Public PriceTwo As Double
Than i did this in my form in Close() and Open():
Private Sub Form_Close()
PriceOne = Me.Field
PriceTwo = Me.FieldTwo
End Sub
Private Sub Form_Open(Cancel As Integer)
Me.Field = PriceOne
Me.FieldTwo = PriceTwo
End Sub
Works perfect!
Courtesy of How to save the last value of a textbox. | Access World Forums:
Private Sub Form_Close()
'Set the default value for textbox
DoCmd.SetWarnings False
DoCmd.RunSQL "UPDATE table SET table.field = [Forms]![FormName]![Textbox] " & vbCrLf & _
"WHERE (((table.ID)=1));"
DoCmd.SetWarnings True
End Sub
Private Sub Form_Load()
'Load the default value for textbox
Me.Textbox.Value = DLookup("[field]", "[table]", "[ID]=1")
End Sub

Form Controls not updated from Class methods

I am a newcomer to Visual Studio 2013, so my question is probably -and hopefully- a simple one.
I am currently writing a small program (in VB) that will essentially add/update/delete users from a table.
The main form has three TextBoxes (ID#, name, last name), a button to check if the user already exists and a couple more buttons (Save and Cancel)
I have also created a Class (dataLookup) where all the functions for adding, updating or deleting users are stored.
The way the program works is as follows:
1.- The user enters an ID# in the main Form's ID field and clicks on the "check user" button.
2.- The system calls a function stored in the datalookup Class that verifies if the ID# already exists.
3.- If it does, the function retrieves the name and last name from the table, assigns them to two local variables (vName and vLastName) populates the corresponding fields on the Main Form and returns TRUE. User can then either update data or Cancel (See code sample below)
MainFormName.TextBox1.Text = vName
MainFormName.TextBox2.Text = vLastName
return True
4.- If the ID# doesn't exist, the function returns FALSE. User is then able to enter new data in the three textboxes.
My problem is that I can't populate the TextBox fields from the function stored in the dataLookup Class. After the instructions are processed, the TextBoxes (which are both Enabled and have their Read Only property set to false) remain empty.
If I add the exact same code that populates the fields to the Main Form code, and assign values to the vName and vLastName variables, it works perfectly:
vName = "John"
vLastName = "Doe"
MainFormName.TextBox1.Text = vName
MainFormName.TextBox2.Text = vLastName
FYI, no errors are reported when I compile/run the program.
I am aware that I can modify the function so it will also return the name and last name and then I will be able to update the TextBox fields from the Main Form, but I am just curious: Why can't I do that from the function stored in the Class?
Hope my description was reasonably clear :) Any help will be much appreciated. Many thanks in advance!
Randy
Forms are classes (it says so at the top of each of them):
Public Class MainForm
....
As a class, an instance should be created however, VB allows what is called a default instance using the class name: MainForm.Show()
Under the hood, the compiler creates an instance of MainForm named MainForm and uses it. This is handy for developers hobbyists dabbling in code, but there are numerous ways this can bite you:
Sub DoSomeThing()
Dim frm As New Form1
frm.TextBox1.Text = cp.ToString
End Sub
Here a local instance of Form1 is created and used which has no relation to the Global Form1 which VB created. The local object goes out of scope at the end of the Sub never to be used by the rest of the app.
' in sub main:
Application.Run(New Form1) ' main form/pump
... elsewhere
Form1.TextBox1.Text = "hello, world!"
In spite of using the same name, these are actually different instances. The text will not show up and if the next line was Form1.Show(), a second copy of Form1 would display complete with the 'hello, world' text. These will also create/show new instances:
Form2.Show()
' or
Dim frm As New Form2
frm.Show()
In general, the more complex the app, the less appropriate using default instances is. For serious apps, create explicit form instances:
Dim myFrm = New Form7() ' myFrm is an instance of Form7
...
myFrm.TextBox1.Text = vName
myFrm.TextBox2.Text = vLastName
myFrm.Show
Classes or other forms can be told about this form various ways such as via a property or the constructor:
Class Foo
Private myFrm As Form7
Public Sub New(frm As Form7)
myFrm = frm
End Sub
...
End Class
Dim myFoo = New Foo(Me)
For the main/startup form, it can help to create a global reference:
Module Program
Friend frmMain As MainForm
End Module
Then set the variable when the main form loads:
Public Class MainForm
Private Sub MainForm_Load(sender ...)
frmMain = Me
End Sub
...
frmMain will be a valid reference to the main form for the entire application.

How to change the title bar text of a Userform in VBA?

I'm maintaining an old-ish application written in VBA for Excel 2002 (XP)/2003, and am trying to internationalise it.
To do this, I read in the translated strings dynamically and update the various controls on my userform by updating their .Caption property.
This works as expected for all controls but not for the form itself -- when I change the form's .Caption property, then the title bar keeps displaying the "hard-coded" value, and the new value is instead displayed just below it, at the top of the "canvas" of the form itself.
Is it possible to change the title bar text of a UserForm after it has been shown, or do I have to change the .Caption property of the form before it is shown in order for it to be reflected in the title bar rather than in the canvas/client area?
My code looks something like this:
' in frmFoo
Private Sub UserForm_Activate()
' ...
TranslateDialog Me, "frmFoo"
' ...
End Sub
' in a VBA module
Sub TranslateDialog(pForm As UserForm, pFormName As String)
Dim new Caption As String
Const notFound As String = "###!!##NOTFOUND##!!###"
' ...
' GetMessage() returns the translated message for a given key, or the
' default value (second parameter) if no translation is available.
' The translation key for the form caption is the form name itself.
newCaption = GetMessage(pFormName, notFound)
If newCaption <> notFound Then pForm.Caption = newCaption
' ...
End Sub
As I said, the assignment to pForm.Caption does have an effect - but it doesn't write to the title bar of the window, but rather directly beneath it. I'm running Excel 2003 on Windows XP SP 3.
Your frmFoo is not actually the same type as the base UserForm, rather it's internally "descended" from it in VBA's wierd OO implementation so you can't use that reliably as a parameter type, using Object instead will work;
Sub TranslateDialog(pForm As Object, pFormName As String)

Invalid cast exception

I have a simple application to store address details and edit them. I have been away from VB for a few years now and need to refreash my knowledge while working to a tight deadline. I have a general Sub responsible for displaying a form where user can add contact details (by pressing button add) and edit them (by pressing button edit). This sub is stored in a class Contact. The way it is supposed to work is that there is a list with all the contacts and when new contact is added a new entry is displayed. If user wants to edit given entry he or she selects it and presses edit button
Public Sub Display()
Dim C As New Contact
C.Cont = InputBox("Enter a title for this contact.")
C.Fname = frmAddCont.txtFName.Text
C.Surname = frmAddCont.txtSName.Text
C.Address = frmAddCont.txtAddress.Text
frmStart.lstContact.Items.Add(C.Cont.ToString)
End Sub
I call it from the form responsible for adding new contacts by
Dim C As New Contact
C.Display()
and it works just fine. However when I try to do something similar using the edit button I get errors - "Unable to cast object of type 'System.String' to type 'AddressBook.Contact'."
Dim C As Contact
If lstContact.SelectedItem IsNot Nothing Then
C = lstContact.SelectedItem()
C.Display()
End If
I think it may be something simple however I wasn't able to fix it and given short time I have I decided to ask for help here.
I have updated my class with advice from other members and here is the final version (there are some problems however). When I click on the edit button it displays only the input box for the title of the contact and actually adds another entry in the list with previous data for first name, second name etc.
Public Class Contact
Public Contact As String
Public Fname As String
Public Surname As String
Public Address As String
Private myCont As String
Public Property Cont()
Get
Return myCont
End Get
Set(ByVal value)
myCont = Value
End Set
End Property
Public Overrides Function ToString() As String
Return Me.Cont
End Function
Sub NewContact()
FName = frmAddCont.txtFName.ToString
frmStart.lstContact.Items.Add(FName)
frmAddCont.Hide()
End Sub
Public Sub Display()
Dim C As New Contact
C.Cont = InputBox("Enter a title for this contact.")
C.Fname = frmAddCont.txtFName.Text
C.Surname = frmAddCont.txtSName.Text
C.Address = frmAddCont.txtAddress.Text
'frmStart.lstContact.Items.Add(C.Cont.ToString)
frmStart.lstContact.Items.Add(C)
End Sub
End Class
You're doing
frmStart.lstContact.Items.Add(C.Cont.ToString)
That is, you are adding strings to lstContact. Of course lstContact.SelectedItem() is a string!
Since you didn't post all of your code, I'll give you my best guess which is:
lstContact seems like it is bound to an IEnumerable of strings instead of IEnumerable of Contacts.
Therefore, when you get lstContact.SelectedItem() it is returning a string instead of a Contact (and throwing an error when trying to cast string as Contact).
It'd be more helpful if you could post the code bit that binds lstContact to a data source.