Display data from SQL server to listvew - sql-server

i'm geek in vb.net, I already make vb.net from application with ms access data base. now i need to use this application for multi user and i want to use SQL server, i use this code to show data from access data base to listview :
con.ConnectionString = "provider=microsoft.ace.oledb.12.0; data source = |datadirectory|\noorapp.accdb;"
con.Open()
Dim dt As New DataTable
Dim ds As New DataSet
ds.Tables.Add(dt)
Dim da As New OleDbDataAdapter("select * from " & Year(Now) & " where cmonth='" & m & "' order by cdate DESC", con)
da.Fill(dt)
Dim myrow As DataRow
For Each myrow In dt.Rows
ListView1.Items.Add(myrow.Item(0)).ToString()
ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(myrow.Item(2))
ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(myrow.Item(3))
ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(myrow.Item(4))
ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(myrow.Item(5))
ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(myrow.Item(6))
ListView1.Items(ListView1.Items.Count - 1).SubItems.Add(myrow.Item(7))
Next
any solution to how make this work for sql server also?
thanks.

change your connection string see here. Also change your OleDbConnection object to SQLConnection and your OleDbDataAdapter to SQLDataAdapter
Your database must already exist in the SQL Server for this to work

Related

SQL Server database population pre-existing Data Table and fields (FORM). NO database file

Here is my general understanding of database from what I read so far: Save / Update / Delete to pre-existing file made that binds to form thru SQL.
Here is what I am trying to do - I have a pre-made Data Table in Form with all columns defined. Once app is closed or certain functions ran, I need that data to be saved / updated in SQL (on local). Once app is open I need all that data to be preserved.
So far I have NOT found a single solution to it anywhere most refer to binding to an existing file. When I worked with Excel data transfer cells had to be defined and referenced in form for population.
My assumption is when a database from VB.NET is used, table with values can be created automatically saved/loaded/updated. However this is only my assumption since I never worked with SQL before. I am not sure if I need to manage an actual database file I created with all the values and then bind them to data table. For example DataTable cell XX to database column XX.
Here is what I done so far I have created database and added to my project. I tried few codes and I keep getting Dataset Empty even though there is Data in Table I tried to use DataTable as well but so far nothing has worked.
Please suggest on what I am doing wrong also additional information regards to databases will be great. As per previous I do know how binding works when actual file exist. But creating and managing is confusing to me since I keep thinking there should be a binding file.
Dim connetionString As String
Dim sqlCnn As SqlConnection
Dim sqlCmd As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim sql As String
connetionString = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Data_Ant.mdf;Integrated Security=True;Connect Timeout=30"
sql = "SELECT BN FROM DataTable" ' BN is my column name and DataTable is the name of my Table where data gets populated. This is also confusing to me How does it know which value is what? Is there are space/word/characters requirements?
' adapter.TableMappings.Add("DataTable", sql)
If ds.Tables.Count > 0 Then
sqlCnn = New SqlConnection(connetionString)
Try
sqlCnn.Open()
sqlCmd = New SqlCommand(sql, sqlCnn)
adapter.SelectCommand = sqlCmd
adapter.Update(ds)
adapter.Dispose()
sqlCmd.Dispose()
sqlCnn.Close()
Catch ex As Exception
MsgBox("Can not open connection !" & vbCrLf & Err.Description)
End Try
ElseIf ds.Tables.Count = 0 Then
MsgBox("Empty data")
End If
End Sub
Code I use to Create /Save Database. As per previous all columns/formats are pre-made, loaded.
Dim connetionString As String
Dim sqlCnn As SqlConnection
Dim sqlCmd As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim sql As String
connetionString = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Data_Ant.mdf;Integrated Security=True;Connect Timeout=30"
sql = "Select BN FROM DataTable"
adapter.TableMappings.Add("BN", sql)
If DataTable.RowCount > 0 Then
sqlCnn = New SqlConnection(connetionString)
Try
sqlCnn.Open()
sqlCmd = New SqlCommand(sql, sqlCnn)
adapter.SelectCommand = sqlCmd
adapter.Update(ds, "BN")
adapter.Dispose()
sqlCmd.Dispose()
sqlCnn.Close()
Catch ex As Exception
MsgBox("Can not open connection !" & vbCrLf & Err.Description)
End Try
ElseIf DataTable.RowCount = 0 Then
MsgBox("Empty data")
End If
End Sub
Please see more info below:
Data Table columns/format are structured for visual representation.
When User start the App Database can be empty/Can contain Values.
When users Runs certain function Closes App values are save and only values.
If I would you an MS Access I would structure same table/values and cross reference it with form values. Form Values come from outside source and Format/Qty is always known.
Hope this helps to have a cleaner look at my issue. Perhaps SQL is not a right choice for me? Does SQL needs to be build before value manipulation.
UPDATE: I Got rid of the Invalid Object error. Table had to be created 1st as I originally thought. However, My DataSet always comes up as EMPTY when I try to save... Cells do contain BN data as" 1,2, ....) Even if I to remove "If" logic Save and Load table comes out as empty. Something does load because when I try to ADD BN it tells me binding bla bla bla(different issue)
CODE:
Private Sub SaveData()
Dim connetionString As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Data_Ant.mdf;Integrated Security=True;Connect Timeout=30"
Dim sql As String = "SELECT BN FROM DataTable_d"
Dim sqlCnn As SqlConnection
Dim sqlCmd As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet()
adapter.TableMappings.Add("BN", sql)
If ds.Tables.Count > 0 Then
sqlCnn = New SqlConnection(connetionString)
Try
sqlCnn.Open()
sqlCmd = New SqlCommand(sql, sqlCnn)
adapter.SelectCommand = sqlCmd
adapter.Update(ds, "BN")
adapter.Dispose()
sqlCmd.Dispose()
sqlCnn.Close()
Catch ex As Exception
MsgBox("Can not open connection !" & vbCrLf & Err.Description)
End Try
ElseIf ds.Tables.Count = 0 Then
MsgBox("Empty data")
End If
End Sub
UPDATE: I got all the things working but I can't save multiple rows..... Could really use some help
In your SQL query remove WHERE DataTable ='. This statement is looking for a column name DataTable which I assume does not exist. The WHERE clause is used to help filter your query. You only use WHERE on column names in your table.
For instance:
SELECT BN FROM DataTable
will return all values from the BN column from DataTable.
Note that if you have multiple columns, the above query will still only return values from BN.
SELECT * FROM DataTable
will return every value in DataTable.
A helpful site to look at documentation for SQL is w3schools.
Let's start with just displaying some data. Add a DataGridView to a Form. You can call LoadData() from a button. I am not very sure of you connection string but give it a try.
Private dt As DataTable
Private sql As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Data_Ant.mdf;Integrated Security=True;Connect Timeout=30"
Private Sub LoadData()
'***EDIT*** Add instantiation line
dt = New DataTable()
'The Using...End Using blocks will close and dispose your database objects
'even if there is an error
Using cn As New SqlConnection(sql)
'You can pass the command text and the connection directly to the constructor
'In the select statement use the actual names of the field and table as they appear in the database.
Using cmd As New SqlCommand("Select BN From [Insert the name of the table in the database]", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
DataGridView1.DataSource = dt
End Sub
This is the simplest way I can think of to display data. We will proceed with changing the data once this works. If you get an error on cn.Open() We will have to work on the connection string.
****EDIT****
Private Sub TestConnection()
Dim sql As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Data_Ant.mdf;Integrated Security=True;Connect Timeout=30"
Using cn As New SqlConnection(sql)
cn.Open()
End Using
End Sub

Inserting contents of CSV file into database loses 1 record

I have an application that imports a CSV file (no header row) and writes the contents into a datatable. The datatable is then passed on as a parameter to a function in my DAL that uses the sqlBulkCopy command to write the data to a SQL Server database.
I have run tested the code as both a Webforms and Windows Forms environment and noticed that in both cases the first row of data is lost. Does anyone know why this should be the case and how I can rectify it? Thanks for any help.
I should add that this doesn't happen if the CSV file has a header row.
UI
Dim csvFileFolder As String = "D:\PROJECTS\Letters(DOTNET)\TextFiles\"
Dim csvFileName As String = "quad1a.txt"
Dim connString As String = "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" _
& csvFileFolder & ";Extended Properties=""Text;HDR=No;FMT=Delimited"""
Dim conn As New Odbc.OdbcConnection(connString)
'Open a data adapter, specifying the file name to load
Dim da As New Odbc.OdbcDataAdapter("SELECT * FROM [" & csvFileName & "]", conn)
'Then fill a data table, which can be bound to a grid
Dim dt As New DataTable
da.Fill(dt)
grdQuad.DataSource = dt
grdQuad.DataBind()
LettersBLL.TemporaryPatientManager.InsertIntoBulkTable(dt)
DAL
Public Shared Function InsertIntoBulkTable(dt As DataTable) As DataTable
Using myConnection As New SqlConnection(ApplicationConfiguration.ConnectionString)
Using sqlBulkCopy As New SqlBulkCopy(myConnection)
'Set the database table name
sqlBulkCopy.DestinationTableName = "tblBulkInsert"
myConnection.Open()
sqlBulkCopy.WriteToServer(dt)
myConnection.Close()
End Using
End Using
Return Nothing
End Function
Try this...
Dim connString As String = "Driver={Microsoft Text Driver (*.txt; *.csv)};HDR=No;Dbq=" _& csvFileFolder & ";Extended Properties=""Text;HDR=No;FMT=Delimited"""
Added 'HDR=No' to your connection string
Or try specifying your sqlbulkcopy column mappings.
msdn.....
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.columnmappings.aspx
Example.....
http://www.codeproject.com/Articles/18418/Transferring-Data-Using-SqlBulkCopy

vb write information from SQL Server database

I use visual basic 2008 and a SQL Server database. I want to write the information stock in the database and I want to be rank like in php I use table to rank information what the method to do that in vb. This code write only last information into the table tbl_cars
Dim da As SqlDataAdapter
Dim dt As DataTable
Dim sqlconn As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\m7md\Documents\Visual Studio 2008\Projects\Cars\Cars\cars.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True")
dt = New DataTable
da = New SqlDataAdapter
Dim sql As String = ("select * from tbl_cars ")
da = New SqlDataAdapter(sql, sqlconn)
sqlconn.Open()
da.Fill(dt)
For Each drRow As DataRow In dt.Rows
Label6.Text= (drRow.Item("db_type").ToString)
Label7.Text = (drRow.Item("db_gender").ToString)
Label8.Text = (drRow.Item("db_color").ToString)
Label9.Text = (drRow.Item("db_price").ToString)
Next
End Sub

retrieving data in VB from SQL

I use Visual Basic 2010 and Microsoft SQL Server 2008. I have my database and my table and i made the connection (at least i think i did) in VB using only the interface.
What i want to know is how to get data from the database and use it into my VB project. I have of course searched for solutions already but the differences i find only confuse me more. What i need to know are the basics, the tools/objects and procedures to retrieve the data.
What i try to do at the moment is make a simple selection and put that data into a listbox right when the program starts, like this:
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SqlConnection1.Open()
SqlConnection1.Close()
End Sub
End Class
1) Create your connection string
Dim connectionString As String = "Data Source=localhost;........."
2) Connect to your Database
Dim connection As New SqlConnection(connectionString)
conn.Open()
3) Create a Command and the query
Dim command As New SqlCommand("SELECT * FROM Product", connection)
Dim reader As SqlDataReader = command.ExecuteReader() //Execute the Query
4) Retrieve your result. There are several ways
Dim dt As New DataTable()
dt.Load(reader)
'Close the connection
connection.Close()
5) Bind to your list box
myListBox.ItemSource = dt
Full code here
Using connection As New SqlConnection(connectionString)
Dim command As New SqlCommand("Select * from Products", connection)
command.Connection.Open()
SqlDataReader reader = command.ExecuteReader()
End Using
For more info
SQLCommand
SqlConnection1.Open()
using table As DataTable = New DataTable
using command as SqlCommand = New SqlCommand("SELECT blah blah", SqlConnection1)
using adapter As SqlDataAdapter = new SqlDataAdapter(command)
adapter.Fill(table)
end using
end using
for each row As DataRow in table.Rows
' add each listbox item
listbox1.Items.Add(row("column name"))
next
end using
SqlConnection1.Close()

Directory pointing to self /creating application with a built-in database

I made a simple program with a database connection:
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim ds As New DataSet 'holds table data
Dim da As OleDb.OleDbDataAdapter 'connection to database connectionobject
Dim sql As String
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = C:/JIMMY.mdb"
con.Open()
sql = "select * from TURNING"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "RECORDS")
con.Close()
Now I heard from someone that in order to make an application with a built in database, I should place the file inside the project.
C:\Users\User\documents\visual studio 2010\Projects\myProject\JIMMY.MDB
How do I make the directory dynamic? So, wherever I place the published application, will it work?
You can make it relative to the application, as explained in HOW TO: Determine the Executing Application's Path:
Dim path As String
path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)
dbSource = "Data Source = " + Path.Combine(path, "jimmy.mdb")

Resources