how to change selected option of textbox based on datareader result vb - vb.net

.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

Related

Update From DataGridView to Database

Dim sb As New MySqlConnectionStringBuilder
sb.Server = Form1.hostname.Text
sb.UserID = Form1.rootuser.Text
sb.Password = Form1.rootpassword.Text
sb.Database = Form1.hostdb.Text
sb.Port = Form1.hostport.Text
Using connection As New MySqlConnection(sb.ConnectionString)
Try
connection.Open()
Dim adapter1 As New MySqlDataAdapter(TextBox1.Text, connection)
Dim cmdb1 = New MySqlCommandBuilder(adapter1)
Dim ds As New DataSet
Dim words As String() = TextBox1.Text.Split(New Char() {" "c})
Dim tablenamewords = (words(3))
adapter1.Update(ds, tablenamewords)
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
connection.Dispose()
End Try
End Using
It's giving me this error:
Update unable to find TableMapping['creature_template'] or DataTable 'creature_template'.
I want to select items then use a DataGrid to update them.
Note: tablenamewords = "creature_template"
You can solve this in alot of different methods.
I prefer to update the DB with a single query every time the the user ends editing a cell.
BUT FIRST you have to bind a source to your DataGridView!
How to bind a source:
Go to your application design an click on your DataGridView
Click on the pause/start like little button as shown:
Click on the "ComboBox" like textbox labeled as "chose data source" as shown and click on it:
It will open a "form", click on the Add data source as shown:
Follow the wizard, you can do it without any furhter explanation!
Well done, you almost completed it. Just go in your code, and look for this sub:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.your_table_nameTableAdapter.Fill(Me.your_db_nameDataSet.your_table_name)
End Sub
The line inside your Form1_Load Sub will upload the data inside your DataGridView, leave it there if you want it to load with the form or cut/paste it wherever you like.
Now you can add this the code to programmatically update the DB:
Private Sub DataGridView1_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
Try
Dim location As Point = DataGridView1.CurrentCellAddress
Dim sqlCmd As String = "UPDATE table_name SET " & _
DataGridView1.Columns(location.X).Name.Replace("DataGridViewTextBoxColumn", "") & " = #Data " & _
"WHERE " & _
DataGridView1.Columns(0).Name.Replace("DataGridViewTextBoxColumn", "") & " = #ID"
Using myConn As New SqlConnection(My.Settings.VISURE_DA_PDFConnectionString)
myConn.Open()
Using myCmd As New SqlCommand(sqlCmd, myConn)
myCmd.Parameters.Add("#Data", SqlDbType.VarChar)
myCmd.Parameters.Add("#ID", SqlDbType.Int)
myCmd.Parameters("#Data").Value = DataGridView1.Rows(location.Y).Cells(location.X).Value
myCmd.Parameters("#ID").Value = DataGridView1.Rows(0).Cells(location.X).Value
myCmd.ExecuteNonQuery()
End Using
myConn.Close()
End Using
Catch ex As Exception
Err.Clear()
End Try
End Sub
Remarks:
location.X is the col index, location.Y is the row index
DataGridView1.Columns(0).Name This is my ID (primary key) and it is always in the first column. Change it with yours.
Don't forget to add .Replace("DataGridViewTextBoxColumn", "") whan you are getting your column name
As previously said, this code will update your DB every time the user edits one cell on your DataGridView updating only the edited cell. This is not a big issue because if you want to edit two ore more cell, every time you leave an edited cell the method DataGridView1_CellEndEdit is fired!

How to create a txt file that records login details? VB.NET

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

Populate datagridview of another form VB.NET

In an attempt to fix my previous problem, i tried to move Form2's(contacts) load event codes to form1's background worker...The code is :
Private Sub Contact_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Con.open
dim cmd as new sqlcommand("Select * from Users",con)
Dim adapter As New SqlDataAdapter(cmd)
Dim table As New DataTable
adapter.Fill(table)
datagrid2.DataSource = table
con.Close()
datagrid2.Columns(0).Frozen = True
datagrid2.Columns(0).Width = 48
datagrid2.Columns(1).Width = 33
AddSelectAllCheckBox(datagrid2)
Dim img As DataGridViewImageColumn
img = datagrid2.Columns(1)
img.ImageLayout = DataGridViewImageCellLayout.Stretch
ExtensionMethods2.DoubleBuffered(datagrid2, True)
ExtensionMethods1.DoubleBuffered(Panel3, True)
ExtensionMethods1.DoubleBuffered(Panel9, True)
mymy1.DoubleBuffered(inpeople, True)
If datagrid2.Rows.Count <= 0 Then
added.Visible = True
Else
added.Visible = False
End If
Try
MetroComboBox2.Items.AddRange(File.ReadAllLines(Application.StartupPath + "\ct_list.ofptx"))
moneylist.Items.AddRange(File.ReadAllLines(Application.StartupPath + "\cr_list.ofptx"))
ttlist.Items.AddRange(File.ReadAllLines(Application.StartupPath + "\tt_list.ofptx"))
Catch ex As Exception
MsgBox("One or more files required by OffPo is missing/corrupted" & vbCrLf & "" & vbCrLf & "Error occured in : ct_list.ofptx or cr_list.ofptx")
End Try
entrylabel.Text = "There are/is " & datagrid2.Rows.Count & " contact entries"
svbtn.Enabled = False
upbtn.Enabled = False
dtb.Enabled = False
End Sub
To fix my previous problem(to fix the BACKGROUND WORKER FREEZING UI issue), i moved this code to the form1's BackGroundWorker's DoWork event. The code for RunCompleted event looks like this :
Private Sub BackgroundWorker2_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker2.RunWorkerCompleted
Contact.Show()
waiting.Hide()
End Sub
The problem is, when BackGroundWorker shows the Form2(contacts), the datagridview becomes empty.It only loads the column names but no rows/data...What am i missing ?? Why isn't the dgvw populating ?
I didn't add the BackGroundWorker Do_work event's code as it is the same as Form2's load event code

vb.NET: Textbox TextChange

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

Subroutine not firing

I have the following subroutines:
Private Sub Exceptionquery()
Dim connection As System.Data.SqlClient.SqlConnection
Dim connectionString As String = "Initial Catalog=mdr;Data Source=xxxxx;uid=xxxxx;password=xxxxx"
Dim _sql As String = "SELECT [Exceptions].Employeenumber,[Exceptions].exceptiondate, [Exceptions].starttime, [exceptions].endtime, [Exceptions].code, datediff(minute, starttime, endtime) as duration INTO scratchpad3 " + _
"FROM [Exceptions]" + _
"where [Exceptions].exceptiondate between #payperiodstartdate and payperiodenddate" + _
"GROUP BY [Exceptions].Employeenumber, [Exceptions].Exceptiondate, [Exceptions].starttime, [exceptions].endtime," + _
"[Exceptions].code, [Exceptions].exceptiondate"
connection = New SqlConnection(connectionString)
connection.Open()
Dim _CMD As SqlCommand = New SqlCommand(_sql, connection)
_CMD.Parameters.AddWithValue("#payperiodstartdate", payperiodstartdate)
_CMD.Parameters.AddWithValue("#payperiodenddate", payperiodenddate)
connection.Close()
End Sub
Public Sub exceptionsButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles exceptionsButton.Click
Exceptionquery()
Dim connection As System.Data.SqlClient.SqlConnection
Dim adapter As System.Data.SqlClient.SqlDataAdapter = New System.Data.SqlClient.SqlDataAdapter
Dim connectionString As String = "Initial Catalog=mdr;Data Source=xxxxx;uid=xxxxx;password=xxxxx"
Dim ds As New DataSet
Dim _sql As String = "SELECT * from scratchpad3"
connection = New SqlConnection(connectionString)
connection.Open()
Dim _CMD As SqlCommand = New SqlCommand(_sql, connection)
_CMD.Parameters.AddWithValue("#payperiodstartdate", payperiodstartdate)
_CMD.Parameters.AddWithValue("#payperiodenddate", payperiodenddate)
adapter.SelectCommand = _CMD
Try
adapter.Fill(ds)
If ds Is Nothing OrElse ds.Tables.Count = 0 OrElse ds.Tables(0).Rows.Count = 0 Then
'it's empty
MessageBox.Show("There was no data for this time period. Press Ok to continue", "No Data")
connection.Close()
Exceptions.saveButton.Enabled = False
Exceptions.Show()
Else
connection.Close()
Exceptions.Show()
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
connection.Close()
End Try
End Sub
and when I press the button:
Public Sub exceptionsButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles exceptionsButton.Click
My subroutine Exceptionquery is not being fired. I know that it's probably something simple that I'm overlooking but don't know what it is. Can someone please assist me with this?
Thank you
Are you sure ExceptionQuery() is being run from exceptionsButton_Click? Your example as shown should work. Step through with the debugger and verify that your button event is actually firing.
it should work, check if the event handler exceptionsButton_Click is called at all and see with a breakpoint if the execution gets into it.
P.S. a small very important detail: the way you are handling the connection is not optimal, you can use a using block, something like this:
using (dim connection as New SqlConnection(connectionString)
...
in this way you are sure connection is closed and disposed when running out of scope and you do not need all those connection.close in the if/else and catch which are wrong anyway the way you did it so far, because if the connection has been closed and you enter the catch and try to close it again, there will be another error.