VB.NET issue loading textboxes with data from SQL Server - sql-server

I have some textboxes (using VS2010) I'm trying to populate with values from columns in a SQL Server database based on what item someone selects from a combobox. At first I was able to display the values for the first item in the combobox, but now nothing at all displays when I debug. Code:
Private Sub loadfields(sender As System.Object, e As System.EventArgs) Handles client_selection_combobox.SelectedIndexChanged
Using myconnection As New SqlConnection("connection string")
Dim loadfields As String = "SELECT company FROM ClientFileDatabase WHERE ClientFileDatabase.File_Name=#company;"
Dim loadfields_sqlcommand As New SqlCommand(loadfields, myconnection)
loadfields_sqlcommand.Parameters.Add("#company", SqlDbType.NVarChar)
loadfields_sqlcommand.Parameters("#company").Value = client_selection_combobox.SelectedIndex.ToString
Dim loadfields_dataadapter As New SqlDataAdapter
loadfields_dataadapter.SelectCommand = loadfields_sqlcommand
Dim loadfields_dataset As DataSet = New DataSet()
loadfields_dataadapter.Fill(loadfields_dataset, "ClientFileDatabase")
Dim loadfields_dataview = New DataView(loadfields_dataset.Tables("ClientFileDatabase"))
companyname_textbox.DataBindings.Clear()
companyname_textbox.DataBindings.Add("Text", loadfields_dataview, "Company")
taxid_textbox.DataBindings.Clear()
taxid_textbox.DataBindings.Add("Text", loadfields_dataview, "TaxIDNumber")
accountmanager_textbox.DataBindings.Clear()
accountmanager_textbox.DataBindings.Add("Text", loadfields_dataview, "AccountManager")
etc...
End Using
End Sub
I've also tried using the SelectedValueChanged and SelectionChangeCommitted event handlers to no avail. Also tried using a refresh after setting the databindings, didn't help. Any advice welcome, thanks!

I personally like to use datatables, I find them easier to work with. I'm sure you will have more code to check to make sure dt.rows.count > 0 before actually attempting to work with the data, but here is how I would do it.
Dim loadfields_dataadapter As New SqlDataAdapter
Dim dt As New DataTable
loadfields_dataadapter.Fill(dt)
companyname_textbox.text = dt.Rows(0).Item("Company")
taxid_textbox.text = dt.Rows(0).Item("TaxIDNumber")
accountmanager_textbox.text = dt.Rows(0).Item("AccountManager")
Also, keep in mind that NULL fields in the database can cause runtime errors, so you may have to check for those as well.

Related

vb.net as I query Access database and display it in listview?

I'm creating a form where I can do the following:
please see the image
As you can see, I have a txt_id_up and txt_id_dw
in the database I want to make the following query.
SELECT * FROM Tabla1
WHERE ID BETWEEN 3 AND 7;
where txt_id_up = 3, and txt_id_dw = 7;
Dim connection As OleDbConnection
Dim command As OleDbCommand
Dim data_reader As OleDbDataReader
'------------------------------
'connect to ms.access database
connection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data
Source= data\base.accdb;Persist Security Info=False")
connection.Open()
'reading data from Tabla1 table
command = New OleDbCommand("SELECT * FROM Tabla1", connection)
data_reader = command.ExecuteReader
'----------------------------------
'here the code to show in listview1 is missing
'----------------------------------
and in passing I would like to ask another question, can only the following columns be shown in listview?
Name
Account
I clarify that I use the datagridview to see it in general and the listview for queries
I don't know if I get your question but if you want to display Name and Account from your database I suggest you to use DataGridView.
Add a DataGridView control to your form and add this code:
Dim connection As OleDbConnection
Dim command As OleDbCommand
Dim data_adapter As OleDbDataAdapter
'------------------------------
'connect to ms.access database
connection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data
Source= data\base.accdb;Persist Security Info=False")
connection.Open()
'reading data from Tabla1 table
command = New OleDbCommand("SELECT Name, Account FROM Tabla1 WHERE ID BETWEEN 3 AND 7", connection)
data_adapter = New OleDbDataAdapter(command)
'add results to DataGridView1
Dim datatable as New DataTable("Table")
data_adapter.Fill(datatable)
DataGridView1.DataSource = datatable
I may have the 2 text boxes backwards.
Public Class Form3
Private Sub FillListView()
ListView1.BeginUpdate() 'keeps the control from repainting on each addition
Using connection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data
Source= data\base.accdb;Persist Security Info=False")
Dim command As New OleDbCommand("SELECT ID, Name FROM Tabla1 Where ID Between ? And ?;", connection)
command.Parameters.Add("FirstID", OleDbType.Integer).Value = CInt(txt_id_up.Text)
command.Parameters.Add("SecondID", OleDbType.Integer).Value = CInt(txt_id_dw.Text)
connection.Open() 'Open the connection at the last possible minute
Using data_reader = command.ExecuteReader
While data_reader.Read()
Dim li As New ListViewItem()
li.Text = CStr(data_reader.GetValue(0)) 'ID
li.SubItems.Add(CStr(data_reader.GetValue(1))) 'Name
ListView1.Items.Add(li)
Loop
End Using
End Using
ListView1.EndUpdate()
End Sub
End Class
Edit
The BeginUpdate of the ListView control prevents the screen from
repainting every time you add an item. This speeds up the addition
of items.
The Using...End Using block makes sure your connection is closed and disposed
event if there is an error.
I added question marks in the Where clause of your SQL statement.
These are placeholders for parameters in the Access/OleDb provider.
I added the 2 parameters to the Parameters collection of the Command
object. The Add method has a number of overloads. The one used here
takes a name and data type. Then the Value property of the parameter
is set to the numbers in the text boxes. These values are in a text
property so they are strings and need the CInt() to convert to
Integers.
I moved the Open method to directly before the command is executed.
Again the Using...End Using block as explained above.
OOPS! I forgot to add the loop (red face) - Code is now corrected
Inside the loop, create a new ListViewItem. A new item for each
iteration of the loop.
Set the Text property of the ListViewItem to the first column in the reader. Convert it to a string. This should show up in the first column.
Set the first SubItem of the ListViewItem to the second column of
the reader. Again convert to a string. This should show up in the
second column.
Add the ListViewItem to the ListView.
The first End Using will close and dispose your data_reader. The
second End Using will close and dispose your connection.
Very Important! ListView1.EndUpdate() Nothing shows up in the
ListView without this line.
Hope this helps.

Calling selection from Combo box on form to be used in SQL query

I have been able to figure out how to populate my combo box with information pulled from a SQL query. What I need to do now is take the item selected from that combo box and run another query with that info using a button. This is what I have so far.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim myconn As New SqlClient.SqlConnection("server=myserver;UID=User;PWD=Password;database=myDB")
Dim myTable As New DataTable()
Dim myCmd As New SqlCommand()
Dim myAdapter As New SqlDataAdapter(myCmd)
myCmd.Connection = myconn
myCmd.Connection.Open()
myCmd.CommandText = "UPDATE myDB.<*Selected list from combo box*> SET example = x WHERE example = y"
myCmd.ExecuteNonQuery()
myCmd.Connection.Close()
MsgBox("Done!")
End Sub
As you can see the issue is the portion I have named <Selected list from combo box> I am not asking for answers on how to do this, I am asking that you all point me in the right direction if possible.
If I understand your question, I believe all you need to do is build a string for your update statement to concatenate the table name in. Something like this would be functional:
myCmd.CommandText = "UPDATE myDB." & listbox1.SelectedItem.Value & " SET example = x WHERE example = y"
One important thing you want to keep in mind though is that a bad value in your list box could cause you to a security vulnerability called SQL Injection. So within your button procedure you might want to do some validation checks to be absolutely sure that the value in listbox1.SelectedItem.Value is strictly a valid table name that you allow to be updated before just passing it along as a SQL command.

SqlDataAdapter not update database

I am very new to VB 2015. I want to learn about database update command. I try to understand SqlDataAdapter. Could anyone please advise me? As my code below, it run completely with no error, but my database table (WORKSHEET) was not updated.
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim command2 As String
command2 = "Update WORKSHEET set cancel_flag = 'Y' WHERE CNumber LIKE #reversalNumber"
Using con2 As New SqlConnection(WindowsApplication1.My.Settings.SaleCommDatabaseConnectionString)
Using cmd2 As New SqlCommand(command2)
Using oda2 As New SqlDataAdapter
cmd2.Connection = con2
con2.Open()
cmd2.Parameters.Add("#reversalNumber", SqlDbType.VarChar, 10, "15332")
oda2.UpdateCommand = New SqlCommand(command2, con2)
End Using
End Using
End Using
MsgBox("ggggg")
End Sub
End Class
The SqlDataAdapter class is useful for applying changes from a DataSet to the database. Try filling a DataSet with the modified data, and then apply changes using the adapter's update method (oda2.Update(WORKSHEET)).
EDIT: Make sure that you fill the DataSet with the data by using the SqlDataAdapter's Fill method.
oda2.Fill(yourDataSet)
Before this, you need to select the proper command with oda2.SelectCommand = YourCommand.

VB.NET - .accdb database not saving changes

I can't figure out why my code won't save to my .accdb database.
I am fetching data from a .accdb database file and displaying it in a DataGridView, and then allowing changes to be made to it there. (This is a stock control system.) After making changes, the user is meant to be able to send the data back so it is saved in the .accdb file.
I have looked online everywhere and tried multiple different ways of doing this. This is the way I am currently using to solve the problem, but when running the code it does not save to the .accdb file. (However, it throws up no errors.)
Public Class Database
Dim datatable As DataTable
Dim adapter As OleDb.OleDbDataAdapter
Dim dbCon As New OleDb.OleDbConnection
Dim dbProvider As String = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"
Dim dbRsrc As String = "Data Source =" & System.IO.Directory.GetCurrentDirectory & "/Resources/List.accdb"
Dim binding As BindingSource
Dim cmdBuilder As OleDb.OleDbCommandBuilder
Private Sub Database_Load(sender As Object, e As EventArgs) Handles MyBase.Load
dbCon.ConnectionString = dbProvider & dbRsrc
dbCon.Open()
adapter = New OleDb.OleDbDataAdapter("Select * FROM List", dbCon)
datatable = New DataTable
adapter.FillSchema(datatable, SchemaType.Source)
adapter.Fill(datatable)
binding = New BindingSource
binding.DataSource = datatable
dbCon.Close()
StockTable.DataSource = binding
End Sub
Private Sub SaveBtn_Click(sender As Object, e As EventArgs) Handles SaveBtn.Click
'insert validation here
Try
dbCon.ConnectionString = dbProvider & dbRsrc
dbCon.Open()
cmdBuilder = New OleDb.OleDbCommandBuilder(adapter)
adapter.AcceptChangesDuringUpdate = True
adapter.Update(datatable)
dbCon.Close()
Catch ex As Exception
MsgBox(ex.Message.ToString() & " Save Unsuccessful.")
End Try
End Sub
End Class
Not sure where I'm going wrong - when I hit the 'save' button, it should connect to the database, build a SQL query to update it and then update my datatable + .accdb database, right?
To test it, I've tried editing multiple columns and saving it, but when opening the file it still says the same values as it had before.
Any suggestions/pointers? I'm pretty newbie to VB.NET, learnt it about 3 months ago and only just starting to get fully into it.
Many thanks to the user "jmcilhinney" who helped me to reach this answer. I feel highly stupid at not realising that my code was working.
I used
Debug.WriteLine("Update value: " & adapter.Update(datatable))
Debug.WriteLine("Connection str: " & dbProvider & dbRsrc)
to find that my update command worked, and that in fact the output of my database file was in the /bin/ folder. I didn't realise that it used the /bin/ folder, and was looking in the root folder with the .VB files, etc.

delete record from database in listview in vb

I have a problem. In the properties of listview which is checkboxes = "True". Using this checkbox, I want to delete the data in listview and in the database.
Below is the code:
If MessageBox.Show("Do you really want to DELETE this record?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = DialogResult.No Then
MsgBox("Operation cancel", MsgBoxStyle.Information, "Information")
End If
dbSource = "Data Source=LAILATUL-PC\SERVER;Initial Catalog=HotelManagementSystem;Integrated Security=True"
Dim sql As String = "DELETE FROM [Room] WHERE Room_Code = #code"
Using con = New SqlConnection(dbSource)
Using cmd = New SqlCommand(sql, con)
con.Open()
For Each lvItem As ListViewItem In ListViewRoom.Items
If lvItem.Checked Then
cmd.Parameters.AddWithValue("#code", ColumnRoomCode.Text)
cmd.ExecuteNonQuery()
lvItem.Remove()
End If
Next
End Using
End Using
Using above code, only the data in listview is deleted. The data in the database not deleted.
The interface for listviewitem:
Thank you if you all can help me. :)
A Command should be executed to have any effect on the database. You need to add this
cmd.ExecuteNonQuery()
in every loop.
Also the connection could be opened just before entering the loop and should be closed afterward. (Using Statement is recommended here)
Said that, please take a look on Parameterized queries because your code is open to Sql Injections and parsing problems. Also the sql command to delete a record doesn't need a list of fields after the FROM table part.
Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
dbSource = "Data Source=LAILATUL-PC\SERVER;Initial Catalog=HotelManagementSystem;Integrated Security=True"
' Parameterized query
Dim sql As String = "DELETE FROM [Room] WHERE Room_Code = #code"
' Using statement to ensure proper closing and disposing
' of the objects SqlConnection and SqlCommand
using con = New SqlConnection(dbSource)
using cmd = New SqlCommand(sql, con)
con.Open()
' Add a parameter just one time before the loop with an empty string
cmd.Parameters.AddWithValue("#code", "")
For Each lvItem As ListViewItem In ListViewRoom.Items
If lvItem.Checked Then
' Set the parameter value with the value extracted from the ListViewItem
Dim RoomCode = lvItem.Text
cmd.Parameters("#code").Value = RoomCode
cmd.ExecuteNonQuery()
lvItem.Remove()
End If
Next
End Using
End Using
End Sub
One last note. The ColumnRoomCode textbox (?) is always the same, so calling delete one time is enough, but I suppose that this should be changed with some value extrated by you current ListViewItem

Resources