Validating user input in a textbox in Winforms with values in the database - vb.net

I have a windows form page with a textbox. The user needs to enter a "Code" into the textbox and upon a button click a validation should be done. Upon validating that this code exists in the database table a new page should be loaded which will contain details associated with this particular code like the year it was added, the document name, file path etc.
This is my first time programming in VB and I am not entirely familiar with the validation process and how the validation should be done against the database (I am using SQL Server).This is what I have until now:
Private Sub EnterClick_Click(sender As Object, e As EventArgs) Handles EnterClick.Click
Dim oRij As New NICOCrypt.Rijndael
Dim cnn As New SqlClient.SqlConnection(oRij.NICO_RijndaelManaged_Decrypt(ConfigurationManager.AppSettings("ConnectionString")))
Dim cmd As New SqlClient.SqlCommand
Dim oFiles As SqlClient.SqlParameter
cmd.CommandType = CommandType.StoredProcedure
Dim valueExistsInDB As Boolean = CBool(CInt(cmd.ExecuteScalar()) > 0)
cnn.Close()
If valueExistsInDB = True AndAlso txtCode.Text IsNot Nothing Then
End If
End Sub

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

How to represent currently logged in user in vb.net

I am in desperate need of some help.
I'm using SQL Server and vb.net. On my personal info Windows form I'm trying to populate textboxes with user information based on the currently logged in user.
However I don't know how to represent the value of the current user. I'm trying to pass the value as a parameter. What should be put in place of: #idontknow ?
Code for form:
Private Sub PersonalInfo_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim connection As New SqlConnection("server=DESKTOP-PL1ATUA\DMV;Database=EHR;Integrated Security=True")
Dim dt As New DataTable
connection.Open()
Dim sqlcmd As New SqlCommand("SELECT * FROM PATIENT WHERE PATIENT_ID = #id", connection)
Dim sqlda As New SqlDataAdapter(sqlcmd)
Dim user_email As Object = Nothing
sqlcmd.Parameters.AddWithValue("#id", #idontknow)
Dim reader As SqlDataReader = sqlcmd.ExecuteReader()
While reader.Read()
fname.Text = reader("PATIENT_FNAME")
ComboBox1.Text = reader("patient_gender")
TextBox4.Text = reader("patient_street")
TextBox5.Text = reader("patient_city")
TextBox6.Text = reader("patient_state")
TextBox7.Text = reader("patient_zip")
TextBox8.Text = reader("patient_phone")
email.Text = reader("user_email")
End While
End Sub
Here I validate User credentials on a windows form by checking email and password, the primary key (patient_id) is generated upon insert when a new user registers (this code is on a separate form, which is not displayed below):
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connection As New SqlConnection("server=DESKTOP-PL1ATUA\DMV;Database=EHR;Integrated Security=True")
Dim command As New SqlCommand("select * from patient where user_email = #email and user_pass = #pass", connection)
command.Parameters.Add("#email", SqlDbType.VarChar).Value = email.Text
command.Parameters.Add("#pass", SqlDbType.VarChar).Value = pass.Text
Dim adapter As New SqlDataAdapter(command)
Dim table As New DataTable()
adapter.Fill(table)
If table.Rows.Count() <= 0 Then
MessageBox.Show(" Username or Password are Invalid")
Else
MessageBox.Show("Login Successful")
command.CommandType = CommandType.StoredProcedure
dashboard.Show()
End If
End Sub
Your login code queries for a record from the patient table that has the appropriate username and password. Right now it looks like all you're doing is checking for the existence of such a record. What you want to do is take that record's patient_id and store it somewhere that you can refer back to from elsewhere in your code. This could be something as simple as a shared property somewhere. This question discusses a few options that might suit. For instance, a module:
Module CurrentUser
Public Property PatientId As Integer
End Module
Or a class that can't be instantiated:
NotInheritable Class CurrentUser
Private Sub New()
End Sub
Public Shared Property PatientId As Integer
End Class
Review the answers to the question linked above for a discussion of the differences between the two approaches. In either case, you'd assign the value of CurrentUser.PatientId in your login code and then access its value where you've written #idontknow.
One last thing: it looks like your login code is taking the contents of a password box somewhere and comparing it directly to the contents of the password field in your database, which strongly implies that you're storing passwords as plain text. This is not secure. Review this question for a thorough overview of how to store passwords securely.
Well, I'm not sure if you're looking for a logged user in Windows, then it's a string (not Integer) as follows:
Dim UserNameStr As String = Environment.UserName
Same applies to the SQL Server:
SELECT CURRENT_USER;
...it's a string too.

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.

displaying detailed form based on textbox value and a button

i have a form named "search" with 2 textboxes,datagridview and a buttton. when i enter any keyword such as a name i want into the first textbox ["txtemployee_search"], it filters the datagridview [dgvemployee]items which is binded to the employee table.so when i select the name im looking for, it shows up in the second textbox["txtemp_search_selection"].but MY PROBLEM IS, I WANT TO SHOW OR OPEN A SECOND FORM CONTAINING THE DETAILS like name,age,sex,picture,phone,etc which are related to the name in the second textbox WHEN I CLICK THE BUTTON. im using vb 2008 and sql server 2005.I NEED HELP PLS!!!
below is my code
Imports System.Data.SqlClient
Public Class employee_search
'THE CODE TO SEARCH DATAGRID WHILE TYPING INTO FIRST TEXTBOX
Private Sub txtemployee_search_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtemployee_search.TextChanged
Dim keywords As String = txtemployee_search.Text
Dim con As SqlConnection = New SqlConnection("Data Source=oheneba;Initial Catalog=brainiac;Persist Security Info=True;User ID=sa;Password=***********")
' Use wildcard
Dim cmd As SqlCommand = New SqlCommand("SELECT * FROM Employee WHERE Full_Name Like '%" & keywords & "%' ", con)
' or Where Full_Name='" & keywords & "'
con.Open()
Dim myDA As SqlDataAdapter = New SqlDataAdapter(cmd)
Dim myDataSet As DataSet = New DataSet()
myDA.Fill(myDataSet, "Employee")
dgvemployee.DataSource = myDataSet.Tables("Employee").DefaultView
con.Close()
End Sub
'CODE TO DISPLAY SELECTED DATAGRIDVIEW ITEM INTO THE SECOND TEXTBOX
Private Sub dgvemployee_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvemployee.CellContentClick
Dim dgv As DataGridView = CType(sender, DataGridView)
Dim thisCell As DataGridViewCell = dgv.SelectedCells(0)
Dim selCell As Integer = thisCell.ColumnIndex
txtemp_search_selection.Text = dgvemployee.CurrentRow.Cells(selCell).Value.ToString()
End Sub
The approch is a bit diffrent that you should choose.
Sorry if i'm wrong but i'll wive you an example with 2 grids. one with customers and one with orders (the relation must be right on the DB). So use 2 BindingSource objects. one with Customers and one with Orders.
so we have
CustomersBindingSource
OrdersBindingSource
Set on property window
CustomersBindingSource.Datasource = yourDataset
CustomersBindingSource.DataMember = Customers
OrdersBindingSource.Datasource = OrdersCustomersfkBindingSource
and about filtering the way that i suggest is this one:
CustomersBindingSource.filter = "Customername like " & txtCustomFilter
i'm in a little hurry now.. but if you have more questions i'll be happy to help you.
If you want additional details in another form, then what you need to do is create the second form with the details. Add in databinding, just like you did for the datagridview, and navigate to the correct record. You should be able to pass the full name selected from the datagridview into the new form.
tIndex = Me.MyBindingSource.Find("Full_Name", keywords)
If tIndex = -1 Then 'could not find
'employee not found
Else
Me.MyBindingSource.Position = tIndex 'navigate to found record
End If
CODE TO DISPLAY SELECTED DATAGRIDVIEW ITEM INTO THE SECOND TEXTBOX
Try this ..
txtemp_search_selection.Text = dgvemployee.CurrentCell.Value