Good day:)
I have a program with textboxes for Reference Number, Payee, Office and Address... What I want is that if the Reference Number exists in Obligation Table it will automatically put Payee, Office and Address, If not, you will type Payee's name but if exists in Payees table automatically it will put the Office and Address...
my problem is that it displays the correct result BUT a message box saying "No current query in data reader." I think the code are overlapping each other but i don't know how to resolve this.
Here's my code for txtRefNo.Text:
Private Sub txtRefNo_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtRefNo.TextChanged
Try
modGlobalFunctions.Connection.Close()
modGlobalFunctions.connectDatabase()
Reader = modGlobalFunctions.executeQuery("SELECT DISTINCT ref_no, payee from bims_obligations " & _
"WHERE ref_no = '" & txtRefNo.Text & "'")
If Reader.HasRows Then
While Reader.Read
txtPayee.Text = Reader("payee").ToString()
txtOffice.Text = Reader("office").ToString()
txtAddress.Text = Reader("address").ToString()
txtPayee.Enabled = False
txtOffice.Enabled = False
txtAddress.Enabled = False
certALoadGrid()
End While
Else
txtPayee.Clear()
txtOffice.Clear()
txtAddress.Clear()
txtPayee.Enabled = True
txtOffice.Enabled = True
txtAddress.Enabled = True
End If
Reader.Close()
modGlobalFunctions.Connection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "BIMS", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
modGlobalFunctions.Connection.Close()
End Sub
and for txtPayee.text:
Private Sub txtPayee_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtPayee.TextChanged
Try
modGlobalFunctions.Connection.Close()
modGlobalFunctions.connectDatabase()
Reader = modGlobalFunctions.executeQuery("SELECT * from bims_payee " & _
"WHERE payee = '" & txtPayee.Text & "'")
If Reader.HasRows Then
While Reader.Read
txtOffice.Text = Reader("office").ToString()
txtAddress.Text = Reader("address").ToString()
End While
Else
txtOffice.Clear()
txtAddress.Clear()
End If
Reader.Close()
modGlobalFunctions.Connection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "BIMS", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
modGlobalFunctions.Connection.Close()
End Sub
Looking forward for answers... or is there an if statement that if refNo exists then it will disregard textChange of txtPayee??? God bless :)
I believe that this line:
txtPayee.Text = Reader("payee").ToString()
Will cause txtPayee_TextChanged to fire. Which then calls:
modGlobalFunctions.Connection.Close()
modGlobalFunctions.connectDatabase()
You haven't shown us the code for those functions, but the names are certainly suggestive. You then use this global connection object inside txtPayee_TextChanged, and close it again at the bottom.
Finally, the code inside txtRefNo_TextChanged resumes with these lines:
txtOffice.Text = Reader("office").ToString()
txtAddress.Text = Reader("address").ToString()
But that Reader is associated with a connection that's been closed twice (or replaced, in some fashion, again, you've not shown that code) - and you'll have an error.
This is but one reason why having a globally shared Connection object is a bad idea (it's also bad if/when you want to start using background workers, Tasks, or anything else that involves multithreading).
It would be far better to just have a connection string in your modGlobalFunctions module. Then, inside each function, create separate SqlConnection and SqlCommand objects - placing each within Using statements. That way they will not interfere with each other.
I'm guessing that the
modGlobalFunctions.Connection.Close()
Were added at the top of each function to cure an earlier symptom of the same issue
Also, as indicated in my comment - don't catch Ex as Exception and just display Ex.Message. You have no idea what exceptions might be thrown, and you're disposing of a lot of useful information (such as the Stack Trace and Inner Exception)
E.g. this is how I'd write your first sub:
Private Sub txtRefNo_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtRefNo.TextChanged
Using conn As New SqlConnection(ConnectionString) 'Our own private connection, no one else can interfere
Using cmd As New SqlCommand("SELECT DISTINCT ref_no, payee from bims_obligations WHERE ref_no = #RefNo", conn) 'Using parameters, safer SQL
cmd.Parameters.AddWithValue("#RefNo", txtRefNo.Text)
conn.Open() 'Open the connection
Dim Reader = cmd.ExecuteReader()
If Reader.HasRows Then
While Reader.Read
txtPayee.Text = Reader("payee").ToString()
txtOffice.Text = Reader("office").ToString()
txtAddress.Text = Reader("address").ToString()
txtPayee.Enabled = False
txtOffice.Enabled = False
txtAddress.Enabled = False
certALoadGrid()
End While
Else
txtPayee.Clear()
txtOffice.Clear()
txtAddress.Clear()
txtPayee.Enabled = True
txtOffice.Enabled = True
txtAddress.Enabled = True
End If
Reader.Close() 'Not really necessary, but anyway
End Using
End Using 'These have cleaned up our connection and command objects
'If an exception has occurred, we don't know what it is, or how to recover
'So we don't try and catch it.
End Sub
Related
I have a multi-level access login form made in VB.NET that uses an Access database in the back end.
If the user tries to log in when there is nothing entered in either of the text boxes (presses the log in button with nothing entered into either of the text boxes) and then tries to log in after entering their correct details, it allows it.
However, when the user enters either the username or password wrong, it will not allow them to log in after they have entered the correct details.
I am also having a problem where there is no case sensitivity (as long as the password has the correct characters in the correct order it doesn't matter if it is in upper case or lower case).
Imports System.Data.OleDb
Public Class frmLogin
Private DBCon As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" &
"Data Source=|DataDirectory|\NewHotel.mdb;")
Private Sub btnLogIn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogIn.Click
If txtUsername.Text = "" Or txtPass.Text = "" Then
lblErrorEmpty.Visible = True
Else
Try
DBCon.Open()
Using cmd As New OleDbCommand("SELECT * FROM tblEmployees WHERE [Username] = #Usernname AND [Pass] = #Pass", DBCon)
cmd.Parameters.AddWithValue("Username", OleDbType.VarChar).Value = txtUsername.Text.Trim
cmd.Parameters.AddWithValue("Pass", OleDbType.VarChar).Value = txtPass.Text.Trim
Dim DBDA As New OleDbDataAdapter(cmd)
Dim DT As New DataTable
DBDA.Fill(DT)
If DT.Rows(0)("Type") = "Manager" Then
frmHomeManager.Show()
ElseIf DT.Rows(0)("Type") = "Receptionist" Then
frmHomeReceptionist.Show()
End If
End Using
Catch ex As Exception
lblErrorMatch.Visible = True
End Try
End If
End Sub
Thank you for your time :)
Don't declare connections outside of the method where they are used. Connections need to be closed and disposed. Using...End Using blocks handle this even when there is an error.
I have separated the user interface code from the database code. This makes the code easier to maintain
For OleDb the .Add method for parameters will help. Don't open the connection until directly before the .Execute. You are only retrieving a single piece of data so .ExecuteScalar should do the trick.
Private ConStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\NewHotel.mdb;"
Private Sub btnLogIn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogIn.Click
If txtUsername.Text = "" OrElse txtPass.Text = "" Then
MessageBox.Show("Please fill in both User Name and Password")
Exit Sub
End If
Dim UserType As Object
Try
UserType = GetUserType(txtUsername.Text.Trim, txtPass.Text.Trim)
Catch ex As Exception
MessageBox.Show(ex.Message)
Exit Sub
End Try
If UserType Is Nothing Then
MessageBox.Show("No record found")
ElseIf UserType.ToString = "Manager" Then
frmHomeManager.Show()
ElseIf UserType.ToString = "Receptionist" Then
frmHomeReceptionist.Show()
Else
MessageBox.Show($"{UserType} is not listed.")
End If
End Sub
Private Function GetUserType(UserName As String, Password As String) As Object
Dim Type As Object
Using DBCon As New OleDb.OleDbConnection(ConStr),
cmd As New OleDbCommand("SELECT Type FROM tblEmployees WHERE [Username] = #Usernname AND [Pass] = #Pass", DBCon)
cmd.Parameters.Add("#Username", OleDbType.VarChar).Value = UserName
cmd.Parameters.Add("#Pass", OleDbType.VarChar).Value = Password
DBCon.Open()
Type = cmd.ExecuteScalar.ToString
End Using
Return Type
End Function
Your check for the password is case insensitive, because you are storing the password directly and the database is case insensitive.
Your major problem is that you shouldn’t be storing the password in the database, you should be storing a cryptographically secure hash of the password in the database. This will require more work, but will be much safer.
You don’t have enough details to say why you can’t make a second attempt. I will say for reading a single record, I wouldn’t use a data table.
I wanna create a txt file that stores the Username, Password, Date & Time, and User Type when "Log In" button is pressed. But all I know is how to create a txt file. Can anyone help me? Here's my code for my Log In button:
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Dim username As String = ""
Dim password As String = ""
Dim cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=D:\Library Management System\LMS_Database.accdb")
Dim cmd As OleDbCommand = New OleDbCommand("SELECT ID_Number FROM Users WHERE ID_Number = '" & txtUsername.Text & "' AND ID_Number = '" & txtPassword.Text & "'", cn)
cn.Open()
Dim dr As OleDbDataReader = cmd.ExecuteReader()
If (dr.Read() = True And cboUserType.Text = "Student") Then
MsgBox("Welcome!", MsgBoxStyle.OkOnly, "Successfully logged in.")
frmViewBooks.Show()
txtUsername.Clear()
txtPassword.Clear()
cboUserType.SelectedIndex = -1
Me.Hide()
Else
If (txtUsername.Text = "admin" And txtPassword.Text = "ckclibraryadmin" And cboUserType.Text = "Administrator") Then
MsgBox("Welcome, admin!", MsgBoxStyle.OkOnly, "Successfully logged in.")
frmAdminWindow.Show()
txtUsername.Clear()
txtPassword.Clear()
cboUserType.SelectedIndex = -1
Me.Hide()
Else
MsgBox("Your username or password is invalid. Please try again.", MsgBoxStyle.OkOnly, "Login failed.")
txtUsername.Clear()
txtPassword.Clear()
cboUserType.SelectedIndex = -1
End If
End If
End Sub
I'd be getting the Date and Time value from my timer.
Private Sub frmLogIn_Load(sender As Object, e As EventArgs) Handles MyBase.Load
tmrLogIn.Start()
End Sub
Private Sub tmrLogIn_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrLogIn.Tick
lblTime.Text = DateTime.Now.ToString()
End Sub
Thank you!
There are a few things that I'd like to point out to maybe help you later on down the road. Data object generally implement iDisposable, it is a good idea to either wrap them in Using statements or dispose of them manually. Also, it is generally a good idea to wrap any database code into a Try/Catch exception handler because something can go wrong at any point you're trying to access outside data. Also, it is always a good idea to parameterize your query. Finally, you are only wanting to validate that a row is returned from your SQL statement, so your SQL statement should instead return the number of rows returned and then you can use the ExecuteScalar to get that one value returned.
With all of that out of the way, all you would need to do is append a line to a text file using the IO.File.AppendAllLines method using the data you already have if the login was validated.
Here is an example of implementing everything I suggested:
'Declare the object to return
Dim count As Integer = -1
'Declare the connection object
Dim con As OleDbConnection
'Wrap code in Try/Catch
Try
'Set the connection object to a new instance
con = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=D:\Library Management System\LMS_Database.accdb")
'Create a new instance of the command object
'TODO: If [Username] and [Password] are not valid columns, then change them
Using cmd As OleDbCommand = New OleDbCommand("SELECT Count([ID_Number]) FROM [Users] WHERE [Username] = #username AND [Password] = #password", con)
'Parameterize the query
With cmd.Parameters
.AddWithValue("#username", txtUsername.Text)
.AddWithValue("#password", txtPassword.Text)
End With
'Open the connection
con.Open()
'Use ExecuteScalar to return a single value
count = Convert.ToInt32(cmd.ExecuteScalar())
'Close the connection
con.Close()
End Using
If count > 0 Then
'Append the data to the text file
'TODO: Change myfilehere.txt to the desired file name and location
IO.File.AppendAllLines("myfilehere.txt", String.Join(",", {txtUsername.Text, txtPassword.Text, DateTime.Now, cboUserType.Text}))
'Check if it is a student or admin
If cboUserType.Text = "Student" Then
'Inform the user of the successfull login
MessageBox.Show("Welcome!", "Login Successfull", MessageBoxButtons.OK)
frmViewBooks.Show()
ElseIf cboUserType.Text = "Administrator" Then
'Inform the admin of the successfull login
MessageBox.Show("Welcome, admin!", "Login Successfull", MessageBoxButtons.OK)
frmAdminWindow.Show()
End If
'Reset and hide the form
txtUsername.Clear()
txtPassword.Clear()
cboUserType.SelectedIndex = -1
Me.Hi
Else
'Inform the user of the invalid login
MessageBox.Show("Invalid username and/or password. Please try again.", "Invalid Login", MessageBoxButtons.OK)
End If
Catch ex As Exception
'Display the error
Console.WriteLine(ex.Message)
Finally
'Check if the connection object was initialized
If con IsNot Nothing Then
If con.State = ConnectionState.Open Then
'Close the connection if it was left open(exception thrown)
con.Close()
End If
'Dispose of the connection object
con.Dispose()
End If
End Try
Your goal can be achieved in many ways.For example,you can create an access/sql/mysql database to store the required information.But if u want to use a textfile instead,you can store Username,password and other details on seperate lines.Then you can read each line from the text file and use it the way you want.So,which one u prefer? a database or text file? leave a comment and i'lll add the codes/instructions depending on your choice
I use this code for my login form:
Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
Dim ErrorCount As Integer = 0
If (ErrorCount = 3) Then
MessageBox.Show(" The System has been Lock ", " Error! ", MessageBoxButtons.OK, MessageBoxIcon.Error)
Form3.Show()
Else
Dim con As OleDbConnection = New OleDbConnection( _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= UserPass.mdb;")
con.Open()
Dim str As String
str = "SELECT * FROM UserPass WHERE Username='" & txtUsername.Text & "' AND Password='" & txtPassword.Text & "'"
Dim cmd As OleDbCommand = New OleDbCommand(str, con)
cmd.Parameters.AddWithValue("user", txtUsername.Text)
cmd.Parameters.AddWithValue("pass", txtPassword.Text)
Dim sdr As OleDbDataReader = cmd.ExecuteReader()
' It will be case sensitive if you compare usernames here.
If sdr.HasRows Then
If sdr.Read Then
If txtPassword.Text <> sdr("Password").ToString Or txtUsername.Text <> sdr("Username").ToString Then
MessageBox.Show(" Incorrect Username/Password. Login Denied ", " Error! ", MessageBoxButtons.OK, MessageBoxIcon.Error)
ErrorCount = ErrorCount + 1
Else
MessageBox.Show(" You are now Logged In! ", " Welcome! ", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
frmOne.Show()
Me.Hide()
End If
End If
Else
MessageBox.Show(" Incorrect Username/Password. Login Denied ", " Error! ", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
sdr.Close()
con.Close()
End If
What im trying to do is when the user fails to login to the system 3 times, the system will show another form that says the system is locked and the user needs to type in the password from the system to be able to try to log-in again. Kindly help please.
im using ms access as database for the username and password
Combination of two of the other answers. You need to change the declaration to static so that it maintains state. Dim ErrorCount As Integer = 0 to Static ErrorCount As Integer
You also need to add a decrement to the code path where the user has entered an invalid username.
MessageBox.Show(" Incorrect Username/Password. Login Denied ", " Error! ", MessageBoxButtons.OK, MessageBoxIcon.Error)
ErrorCount = ErrorCount + 1 'add this here
Then move the if so that it is after the SQL so move this to after con.close()
If (ErrorCount = 3) Then
MessageBox.Show(" The System has been Lock ", " Error! ", MessageBoxButtons.OK, MessageBoxIcon.Error)
Form3.Show()
Else
Also you seem to have some confusion about parameterized queries. If your using parameterized queries then you don't need to concatenate your SQL which should be
str = "SELECT * FROM UserPass WHERE Username=#user AND Password=#pass"
Also the inside if should never be true under normal conditions
If txtPassword.Text <> sdr("Password").ToString Or txtUsername.Text <> sdr("Username").ToString Then
' this code path is only evaluated if the database ignores the where clause or
' the user changes the username or password textboxs whilst the database connection is proccessing and is therfore unnessacary
MessageBox.Show(" Incorrect Username/Password. Login Denied ", " Error! ", MessageBoxButtons.OK, MessageBoxIcon.Error)
ErrorCount = ErrorCount + 1
Else
MessageBox.Show(" You are now Logged In! ", " Welcome! ", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
frmOne.Show()
Me.Hide()
End If
Finally don't store passwords as plaintext. Use a hash from the System.Security.Cryptography namespace with a salt.
I'm not entirely sure that I understand the question. But this part makes it sound to me like you are trying to lock the computer's entire desktop after a logon attempt in your program has failed three times:
What im trying to do is when the user fails to login to the system 3 times, the system will show another form that says the system is locked and the user needs to type in the password from the system to be able to try to log-in again.
I'm not sure that's a good idea. Wouldn't it be sufficient just to lock the user out of your program instead of locking the entire computer? Think of it like this: there's no reason to inflict a global punishment for a local infraction.
But, putting aside whether or not I think it's a good idea, it's perfectly do-able from VB.NET. All you need to do is call the LockWorkStation function after your counter indicates that three failed login attempts have occurred. This function is provided as part of the Win32 API, so to call it directly from a .NET application, you'll need to use P/Invoke. This function has a relatively simple signature, so its definition shouldn't be too hard to understand either:
<DllImport("user32.dll", SetLastError=True)> _
Public Shared Function LockWorkStation() As Boolean
End Function
This function has some important constraints on its use, namely that it can only be called by processes that are running on the interactive desktop. This is not a problem for you, though, since you're building a GUI application that can only run on the interactive desktop, and you know that if someone has entered an invalid password three times, they're definitely logged in and sitting a few feet from the keyboard.
Invoking the magic from your code is relatively simple, although it's possible for the function to fail and you should handle those error conditions (lest someone find a security backdoor into your application):
If (FailedLogonAttempts < 3) Then
' Do whatever...
Else
' Lock 'em out!
Dim success As Boolean = LockWorkstation()
If Not success Then
' Uh-oh! An error occurred! You need to handle this, otherwise someone
' might be able to gain unauthorized access to the system.
'
' For demonstration and debugging purposes, we'll throw an exception,
' but that's obviously not a secure long-term solution.
Throw New Win32Exception(Marshal.GetLastWin32Error())
End If
End If
If you're just asking how to fix your existing code, the problem is that your ErrorCode variable never goes beyond 0. You've declared it at the top of the btnLogin_Click method like so:
Dim ErrorCount As Integer = 0
That's as a regular variable with method-level scope. That means it is re-initialized (to 0, like you ask it to be) every time that the method runs and does not retain its value.
If you want to declare a variable with method-level scope that does retain its value, you need to declare the variable using the Static keyword, like so:
Static ErrorCount As Integer = 0
A great way to test these things, and figure out what's wrong, is to set a breakpoint inside of the btnLogin_Check method and see exactly what values the variables have! If you did that, you'd notice that each time, ErrorCount is set to 0 after execution passes over the first line. That would be your immediate clue as to what the problem is. Then you just have to figure out how to make the value stick. Now you know you do it using the Static keyword (or moving up a scope, like making it a member of your Form class so that it lives as long as objects of that class).
You can try something like this:
Dim ErrorCount As Int = 0
If (ErrorCount =3) Then
MessageBox.Show(" The System has been Lock ", " Error! ", MessageBoxButtons.OK, MessageBoxIcon.Error)
'Do stuff
'Add Your Code to show new Form something like
Me.Hide()
Form3.Show()
Else
Dim con As OleDbConnection = New OleDbConnection( _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= UserPass.mdb;")
con.Open()
Dim str As String
str = "SELECT * FROM UserPass WHERE Username='" & txtUsername.Text & "' AND Password='" & txtPassword.Text & "'"
Dim cmd As OleDbCommand = New OleDbCommand(str, con)
cmd.Parameters.AddWithValue("user", txtUsername.Text)
cmd.Parameters.AddWithValue("pass", txtPassword.Text)
Dim sdr As OleDbDataReader = cmd.ExecuteReader()
' It will be case sensitive if you compare usernames here.
If sdr.HasRows Then
If sdr.Read Then
If txtPassword.Text <> sdr("Password").ToString Or txtUsername.Text <> sdr("Username").ToString Then
MessageBox.Show(" Incorrect Username/Password. Login Denied ", " Error! ", MessageBoxButtons.OK, MessageBoxIcon.Error)
ErrorCount = ErrorCount + 1
Else
MessageBox.Show(" You are now Logged In! ", " Welcome! ", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
frmOne.Show()
Me.Hide()
End If
End If
Else
MessageBox.Show(" Incorrect Username/Password. Login Denied ", " Error! ", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
sdr.Close()
con.Close()
End If
Best Regards
Imports System.Data.OleDb
Public Class Form1
Private attempt As Integer = 3
Private Sub cmdLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdLogin.Click
Dim cn As New OleDbConnection("Provider=Microsoft.Ace.Oledb.12.0; Data Source=" & My.Application.Info.DirectoryPath.ToString() & "\BackUp\testing.Accdb;")
cn.Open()
If txtpassword.Text = "" Then
MsgBox("Please Enter Your Password !!!", MsgBoxStyle.Critical, "Attention...")
Exit Sub
End If
Dim dr1 As OleDbDataReader
Dim com1 As New OleDbCommand
com1.CommandText = "select [UserID],[Pass] from userinfo where userid = '" & txtUserID.Text & "'"
com1.Connection = cn
If cn.State = ConnectionState.Closed Then cn.Open()
dr1 = com1.ExecuteReader
If dr1.Read Then
If UCase(dr1("Pass")) = UCase(txtpassword.Text) Then
MessageBox.Show("Welecome")
Me.Close()
Else
MessageBox.Show("Wrong Password [" & attempt - 1 & "] Attempt(s) Remaing")
attempt -= 1
txtpassword.Focus()
If attempt = 0 Then
End
End If
End If
Exit Sub
Else
MessageBox.Show("Wrong UserID [" & attempt - 1 & "] Attempt(s) Remaing")
attempt -= 1
txtpassword.Focus()
If attempt = 0 Then
End
End If
End If
cn.Close()
End Sub
Private Sub cmdCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCancel.Click
End
End Sub
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
Me.Dispose()
End Sub
End Class
.hi everyone I have this code:
Private Sub EditPage_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'InventorySysDataSet.tb_master_products' table. You can move, or remove it, as needed.
Me.Tb_master_productsTableAdapter.Fill(Me.InventorySysDataSet.tb_master_products)
sqlCnn = New SqlConnection("Data Source=ZEREY\SQLEXPRESS2008;Initial Catalog=InventorySys;Integrated Security=SSPI")
Me.txtRowId.Text = Form1.txtRowId.Text
'MsgBox(Me.txtRowId.Text)
sql = "Select * from tb_master_inventory_per_day where Inventory_Date = " & txtRowId.Text & ""
Dim upcmd As New SqlCommand("Select * from tb_master_inventory_per_day where Row_Id = #Row_Id", sqlCnn)
upcmd.Parameters.Add(New SqlParameter("#Row_Id", Me.txtRowId.Text))
upcmd.Connection.Open()
Try
Dim dr As SqlDataReader = upcmd.ExecuteReader()
If dr.Read Then
txtInventoryDate.Text = dr.Item("Inventory_Date")
cboProductCode.DisplayMember = dr.Item("Product_Code")
txtQty.Text = dr.Item("Product_Count")
Else
MessageBox.Show("Error!")
End If
Catch ex As SqlException
If ex.Number <> 0 Then
'ErrorProvider1.SetError(Me.txtuseridprofile, "Login Id: " &
'Me.txtuseridprofile.Text & " :Not Found!")
upcmd.Connection.Close()
Exit Sub
End If
End Try
upcmd.Connection.Close()
End Sub
what i want to do is to automatically change the selected option of the cboProductCode on page load depending on the result of a query executed onload also.
help pls! TIA!
.Haha! it's funny that i have tried so many ways but not tried using cboProductCode.Text instead of cboProductCode.DisplayMember. It now works! :D
I have a bound combo box with employee profile names. I have two buttons: save and delete buttons.
When I edit a selected profile, I hit save and automatically the change is reflected in the bound combo box, but when I hit delete or create new profile, I have to close the app and when I open it I see the changes in the bound combo box.
The combobox.Refresh() no work
This is my code:
Private Sub deleteselectedprofile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_deleteprofile_oninsideprofiledittap1.Click
Dim mconn As New SqlConnection("Data Source=(local);Initial Catalog=epmapp_db;Integrated Security=true;")
Dim cmd As New SqlCommand
cmd.Connection = mconn
cmd.CommandType = CommandType.Text
cmd.CommandText = "delete GeneralInfo where RecordId= " + cbox_profiles.SelectedValue.ToString
Try
If MessageBox.Show("¿Está seguro de querer borrar este perfil?", _
"Delete", MessageBoxButtons.YesNo, _
MessageBoxIcon.Warning) = DialogResult.No Then
mconn.Close()
MsgBox("Operación Cancelada")
Else
mconn.Open()
cmd.ExecuteNonQuery()
MessageBox.Show("Su perfil se ha actualizado exitosamete")
Clear_Form_tap1()
disabling_controlstap1()
btn_newprofile_onload_tap1.Visible = True
btn_saveprofile_oninside_profileedit_tap1.Visible = False
btn_editprofile_oncboxselectiontap1.Visible = False
btn_cancelprofileedit_onprofileselectiontap1.Visible = False
btn_deleteprofile_oninsideprofiledittap1.Visible = False
cbox_profiles.Enabled = True
ErrorProvider1.Clear()
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
mconn.Close()
End Try
End Sub
I set my combo box in the Design Tab using the...
Combo Box Task
Use Data Bound Items
Data Binding Mode
Data Source = GeneralInfoBindingDource
Display Member = Nombre
Value Member = RecordId
Selected Value = none
My save button code...
Private Sub btn_saveprofile_oninside_profileedit_tap1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_saveprofile_oninside_profileedit_tap1.Click
Me.Validate()
Me.GeneralInfoBindingSource.EndEdit()
Me.GeneralInfoTableAdapter.Update(Me.Epmapp_dbDataSet)
Try
MessageBox.Show("Su perfil ha actualizado exitosamete")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Clear_Form_tap1()
disabling_controlstap1()
btn_saveprofile_oninside_profileedit_tap1.Visible = False
btn_cancelprofileedit_onprofileselectiontap1.Visible = False
btn_deleteprofile_oninsideprofiledittap1.Visible = False
btn_editprofile_oncboxselectiontap1.Visible = False
btn_newprofile_onload_tap1.Visible = True
cbox_profiles.Enabled = True
ErrorProvider1.Clear()
End Sub
I have try a few codes but none works for me. Can any one help me with a code for this small issue?
If I followed this correctly, when you delete a record you are doing so directly in the database. However, you are not updating your datasource (GeneralInfoBindingDource). My guess is you have the same issue when you create a new item. The database is updated, so when it reloads the data from the database its correct. (When you reopen it).
You need to update your datasource.
Your save works because you are updating the datasource, rather than writing changes to the database without updating it.
Me.GeneralInfoBindingSource.EndEdit()
Me.GeneralInfoTableAdapter.Update(Me.Epmapp_dbDataSet)