Search in form1 and display it to the form2 using vb.net windows form - vb.net

In my form1 I have textbox where the user input their employee_number, and i have a second form where the data of that client will displayed.
This is my first form
Dim dt As New DataTable
Dim EmployeeNumber = EmployeeNumber_TextBox1.Text.Trim()
Try
Using MyCon As New Odbc.OdbcConnection("Driver={PostgreSQL ANSI};database=contacttracing;server=localhost;port=5432;uid=ctadmin;sslmode=disable;readonly=0;protocol=7.4;User ID=*****;password=*****;"),
cmd As New Odbc.OdbcCommand("SELECT firstname FROM ""TracingApp_fmcustomeremployeesupplier"" where employee_number='" & EmployeeNumber & "' ", MyCon)
MyCon.Open()
dt.Load(cmd.ExecuteReader)
EmployeeInformation.Show()
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
how do I do that when the employee enters their number in form1 the data will be displayed in the form2 textbox?
form1
form2
i dont have code yet in my form2 cause i dont know how to get the data from form1 and displayed it to form2

Always use Parameters. User input can be malicious. Parameters indicate to the database that this is only a value not executable code. Parameters help to prevent sql injection.
I changed the names of your controls to match my test program. Of course in your code you would use descriptive names.
In you CommandText, select all the fields you need to display. I had to guess at the names of the fields. Check your database for the correct names. Use the name of the parameter in the Where clause.
When you .Add the parameter check your database for the correct datatype. Since your code had the value of the parameter in single quotes I guessed VarChar. If it is an Int or some other number type be sure to CInt(TextBox1.Text) or whatever datatype you need to change to. You have probably validated the input elsewhere.
Only after the connection and command are disposed do we start using the data returned.
vb.net can work with what is called "the default instance" of forms. That is why this code worked. You can also create you own instance.
dt(0)(0).ToString
This refers to the first row, first column in the DataTable. (Arrays and Collections in .net are zero based)
dt(0)(1).ToString
Refers to the first row, second column or the DataTable and so on.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt As New DataTable
Dim EmployeeNumber = TextBox1.Text.Trim()
Try
Using MyCon As New Odbc.OdbcConnection("Driver={PostgreSQL ANSI};database=contacttracing;server=localhost;port=5432;uid=ctadmin;sslmode=disable;readonly=0;protocol=7.4;User ID=*****;password=*****;"),
cmd As New Odbc.OdbcCommand("SELECT firstname, middlename, lastname FROM ""TracingApp_fmcustomeremployeesupplier"" where employee_number= #empNum' ", MyCon)
cmd.Parameters.Add("#empNum", OdbcType.VarChar).Value = EmployeeNumber
MyCon.Open()
dt.Load(cmd.ExecuteReader)
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Form2.TextBox1.Text = dt(0)(0).ToString
Form2.TextBox2.Text = dt(0)(1).ToString
Form2.TextBox3.Text = dt(0)(2).ToString
Form2.Show()
End Sub

You have at least two more options:
Send an event from Form1 to Form2, which is a safer method. If the user has closed Form2, then Form1 will trigger an exception, unless you check that the form Form2 is indeed loaded and accessible. I think it is more elegant to broadcast an event and let the target form react to it.
Overload the Show (or ShowDialog) method of the target form
You could overload the Show method in Form2 like this:
Public Class Form2
Inherits System.Windows.Forms.Form
Public Overloads Sub Show(ByVal ContactD As Integer)
' load the contact from DB
MyBase.Show()
End Sub
End Class
Basically, you add an alternative declaration for the method. Then in Form1 you instantiate Form2 like this:
Dim frm2 as new Form2
frm2.Show(123456) ' ContactID value
And you let Form2 fetch the data from the DB. So I think sending a contact ID or some primary key is sufficient, but you can send more variables if you want. In this case you could send a DataRow.

Related

VB.Net Combo Box Number from Query

So i have a database with 2 rows code,name lets say its like
code / name
1 / john
2 / george
i use this query to bring them in my combo box .
strConnection = String.Format("Provider=SQLOLEDB;Data Source={0};Initial Catalog={1};User ID={2};Password={3};",
strServer, strDataBase, strUserName, strPassword)
Dim Connection As New OleDbConnection(strConnection)
Connection.Open()
Dim cm As New OleDbCommand("SELECT Codeid [Κωδικός],descr [Περιγραφή] FROM EMBONILO_B.DBO.manufacturer GROUP BY Codeid,descr", Connection)
Dim dr As OleDbDataReader = cm.ExecuteReader
While dr.Read
ComboBox.Items.Add(dr(1).ToString)
End While
dr.Close()
Connection.Close()
and it show the name john and george. What i want is when you click the combo box and you select a name i want the code to appear on the combo box lets say if its george selected i want number 2 in combo box etc.
Thanks for advance.
When you are adding items to the ComboBox you are only setting the Text property, not the Value property. ComboBox.Items.Add() should have an overload where you can do specify the Value as well when you had items in your While loop, something like ComboBox.Items.Add(dr(1).ToString(), dr(0).ToString()) or maybe ComboBox.Items.Add(New ListItem(dr(1).ToString(), dr(0).ToString())) if you are using ASP.NET WebForms for example. Either way, each list item will have separate Text and Value properties; you want to put the ID in the Value property, and you can subsequently get the selected ID in your code using ComboBox.SelectedValue or similar, depending upon the control you are using for a combobox.
My assumption is you really want to obtain the ID in code to store in a db table, not display it in the UI.
This all applies to a WinForms application.
Declare a Form level variable to hold the CodeID of the currently selected descr in the combobox.
Since GetDescriptionData is called from Form.Load the values strServer, strDatabase etc. used in the connection string, must be available at this time. If they are not available until some user input is gathered move the code to a button. .DisplayMember and .ValueMember are names of fields from the Select statement.
Separate the data access code from the user interface code. Connections and commands need to be closed and disposed. Using...End Using blocks take care of that for us.
The form level variable CurrentCodeID is set in the ComboBox.SelectedIndexChanged event.
Private CurrentCodeID As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim ComboDataTable = GetDescriptionData()
ComboBox1.DisplayMember = "descr"
ComboBox1.ValueMember = "Codeid"
ComboBox1.DataSource = dt
End Sub
Private Function GetDescriptionData() As DataTable
Dim dt As New DataTable
Dim strConnection = String.Format("Provider=SQLOLEDB;Data Source={0};Initial Catalog={1};User ID={2};Password={3};",
strServer, strDataBase, strUserName, strPassword)
Using Connection As New OleDbConnection(strConnection),
cm As New OleDbCommand("SELECT Codeid,descr FROM EMBONILO_B.DBO.manufacturer;", Connection)
Connection.Open()
dt.Load(cm.ExecuteReader)
End Using
Return dt
End Function
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
CurrentCodeID = ComboBox1.SelectedValue.ToString
End Sub

Open Form By Variable Value

Form Name comes from a variable. I would like to open Form from variable value.
In VBA load("UserFormName") will show the form. But I don't know how to do it in VB.Net.
Ok, of course one would want to be able to open a form by string name.
When you create a vb.net winforms project, then all forms are available as a "base" static class.
You often see a LOT of code thus simply use the base form class.
If I need to display say form2, then I really don't need to create a instance of that form (unless you want to have multiple instances of that form. So a truckload of code will simply launch + use the "base static" class of that form.
eg:
Form2.Show()
I don't consider this all that bad of a practice, since what do you think the project settings to "set" the startup form in the project settings does?
It simply sets the built in instance of "mainForm" = to your startup form and it does NOT create new instance.
So, now that we all can agree for 15+ years anyone who has set the startup form in their project is NOT creating a NEW instance of that form, but in fact using the base class instance. This is really a programming choice.
So, code to display (show) the base static instance of a form by string name will look like this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim strForm As String = "Form1"
ShowFormByName(strForm)
End Sub
Public Sub ShowFormByName(strFormName As String)
System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(ProductName & "." & strFormName).show()
End Sub
Private Function FormByName(strFormName As String) As Form
Return System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(ProductName & "." & strFormName)
End Function
However, above includes a helper sub that will simply "show" that built in instance of the forms.
And above also includes a function to return class type of the form, since for sure a good many developers prefer to first create a instance of the form, and then "show()" it.
So, often we do want multiple instances, or we just perfer the codeing approach of creating a new instance of the form object.
So, we use the 2nd helper function to return a form object of the type we passed by string.
So, to display 3 instances of form1, but the FIRST instance being the base class, then two more but brand new instances of that form, we have this code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim strForm As String = "Form1"
ShowFormByName(strForm)
Dim f1 As Form = FormByName(strForm)
Dim f2 As Form = FormByName(strForm)
f1.Show()
f2.Show()
End Sub
So the above code snip shows how to display the built in base class form without having to create a instance of that form.
However, the next two forms we load are "new" instances of that form as "string".
So the helper sub, and helper function will give you both choices as to which preference floats your boat.
Dim form = System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(Application.ProductName & "." & MySubForm)
Dim frm As New Form
frm = form
frm.MdiParent = AFrmMainScreen
frm.WindowState = FormWindowState.Maximized
frm.Show()
I prefer to use Reflection.Assembly.GetEntryAssembly because I use several different projects in one solution. This allows me to put this code in a different project(dll) that has a usercontrol that I can then reuse across multiple solutions. You also don't need to know the "Namespace" for the form as long as it is in the startup project.
The code below gets the form type from the exported types from the entry assembly and then uses Activator.CreateInstance to create a new instance of the form. Then I return that form in the function.
Public Function GetForm(ByVal objectName As String) As Form
Try
Dim frmType = Reflection.Assembly.GetEntryAssembly.GetExportedTypes.FirstOrDefault(Function(x) x.Name = objectName)
Dim returnForm = TryCast(Activator.CreateInstance(frmType), Form)
Return TryCast(returnForm, Form)
Catch ex As Exception
Return Nothing
End Try
End Function
To use the above function:
Dim MyForm = GetForm(FormLocation)
If MyForm IsNot Nothing Then
MyForm.ShowDialog()
'You can do any form manipulation from here.
Else
MessageBox.Show($"{FormLocation} was not found.")
End If

How do I transfer data from Text Boxes in a form to an Access Table

I'm currently trying to write code for a form that has text boxes for a user to input the required data into which then with the use of button the data in the text boxes will be sent to an access table.
If you need any more information to help solve the problem I'm willing to provide it if you ask (I would upload pictures/screenshots but I need "10 reputation" apparently.
You can do this
Imports System.Data.OleDb
Public Class Form1
Dim AccessConection As OleDbConnection
Private Sub btSave_Click(sender As Object, e As EventArgs) Handles btSave.Click
Dim cmd As New OleDbCommand
Dim mySql As String
mySql = "INSERT INTO Customs (CustomName,Address) VALUES(#Name,#Address)"
Try
cmd.Parameters.AddWithValue("#Name", txName.Text)
cmd.Parameters.AddWithValue("#Address", txAddress.Text)
cmd.Connection = AccessConection
cmd.CommandType = CommandType.Text
cmd.CommandText = mySql
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Whatever you want to say..." & vbCrLf & ex.Message)
End Try
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim myDataBasePath As String = "C:\Users\user\Source\Workspaces\......\SOF003\Data.accdb" 'Here you put the full name of the database file (including path)
'The next line is for Access 2003 .mdb files
'Dim CadenaConection As String = String.Format("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}", myDataBasePath)
Dim CadenaConection As String = String.Format("Provider=Microsoft.ACE.OLEDB.12.0; Data Source={0}", myDataBasePath)
AccessConection = New OleDbConnection(CadenaConection)
AccessConection.open()
End Sub
End Class
btSave is the command button.
Customs is the table's name.
CustomName and Address are two fields.
txName and txAddress are two TextBox Control.
Obviously you should be careful with the data types (here I use only strings), validation, etc, etc... But, this is a starting point. If you search, you'll find another ways, more elaborated.

Autofill TextBox/Checkbox from a previous TextBox' value (VB.NET Database)

Note: I'm using Visual Studio, original work was on SQL Server, moved to VB.NET
I have a Textbox "ViewStatusTxt", next to it there's a Button "ViewStatusBtn"
Below it there's a TextBox "ViewNAMETxt", another TextBox "ViewACTIVITYTxt" and then a Checkbox "ModifyStatusCB"
I'm trying to auto-fill the Checkbox AND the Textbox based on the ID input there, however I really have no clue about it since I'm new to VB.NET
Here's the code used
Private Sub IDSearch(StatusViewBtn As String)
' ADD SEARCH QUERY PARAMETERS - WITH WILDCARDS
SQL.AddParam("#StatusViewBtn", StatusViewBtn)
'RUN QUERY - SEARCH GIVES THOSE RESULTS
SQL.ExecQuery(" SELECT
aID,
Name,
Status,
Activity
FROM
[dbo].[initialTable]
WHERE
aID = #StatusViewBtn
ORDER BY
aID ASC")
End Sub
That's the function's code, which is fully working since it's a smaller version of the same one I used in a Search Page
Here's the button's function, which I'm sure is where I'm having problems, unless I need to add a specific function to the ViewNAMETxt
Private Sub StatusViewBtn_Click(sender As Object, e As EventArgs) Handles StatusViewBtn.Click
IDSearch(StatusViewBtn.Text)
ViewNAMETxt.Text = SQL.ExecQuery("SELECT
Name
FROM
initialTable
WHERE
aID = #StatusViewBtn")
End Sub
And I haven't even started on the Checkbox, viewing how the first one caused me issues. Hopefully the solution would be similar to both of them.
Thanks for reading guys, and sorry for the newbie question
1- Suppose you have a table named YourTable(int KeyColumn, string StringColumn, boolean BooleanColumn)
2- Create a form and put 2 textboxes and a checkbox and a button on it. KeyColumnTextBox, StringColumnTextBox, BooelanColumnCheckBox, SearchButton
3- In click event handler for SearchButton put the codes:
Private Sub SearchButton_Click(sender As Object, e As EventArgs) Handles SearchButton.Click
Dim connection = New SqlConnection("Your Connection string here")
Dim command = New SqlCommand("SELECT StringColumn, BooleanColumn FROM YourTable WHERE KeyColumn=#KeyColumn", connection)
command.Parameters.Add(New SqlParameter("#KeyColumn", Int32.Parse(KeyColumnTextBox.Text)))
connection.Open()
Dim reader = command.ExecuteReader()
While reader.Read()
StringColumnTextBox.Text = reader.GetString(0)
BooleanColumnCheckBox.Checked = reader.GetBoolean(1)
End While
End Sub
Don't forget to Imports System.Data.SqlClient at top of your file.

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.