how to use recordset movelast - vb.net

i need help for the code that i can use old rs.movelast to vb.net 2010..
any simple way to query my record that automatic select the last..
here is my connection sample i just call it only in any form..///
Public Function ExecuteSQLQuery(ByVal SQLQuery As String) As DataTable
Try
Dim sqlCon As New OleDbConnection(CnString)
Dim sqlDA As New OleDbDataAdapter(SQLQuery, sqlCon)
Dim sqlCB As New OleDbCommandBuilder(sqlDA)
sqlDT.Reset() ' refresh
sqlDA.Fill(sqlDT)
Catch ex As Exception
MsgBox("Error : " & ex.Message)
End Try
Return sqlDT
End Function

sqlDT.rows(sqlDT.rows.count-1) will be the last record of your DataTable sqlDT. sqlDT.rows.count-1 will return you the last index of the rows in the filled table. Hope it will help you. Thanks
Imports System.Data.OleDb
Public Class Form1
Public CnString As String = "Provider=SQLOLEDB;Data Source=HP-PC\SQLEXPRESS;Persist Security Info=True;Password=sa;User ID=sa;Initial Catalog=Accounts"
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim ssql As String = "Select * from TBL_Access"
Dim dt As DataTable
dt = ExecuteSQLQuery(ssql)
TextBox1.Text = dt.Rows(dt.Rows.Count - 1)(0) 'Value of First Column of Last Row of DataTable dt
TextBox2.Text = dt.Rows(dt.Rows.Count - 1)(1) 'Value of Second Column of Last Row of DataTable dt
End Sub
Public Function ExecuteSQLQuery(ByVal SQLQuery As String) As DataTable
Try
Dim sqlCon As New OleDbConnection(CnString)
Dim sqlDA As New OleDbDataAdapter(SQLQuery, sqlCon)
Dim sqlCB As New OleDbCommandBuilder(sqlDA)
Dim sqlDT As New DataTable
sqlDT.Reset() ' refresh
sqlDA.Fill(sqlDT)
Return sqlDT
Catch ex As Exception
MsgBox("Error : " & ex.Message)
Return Nothing
End Try
End Function
End Class

Related

Load data into DataGridView from sql server in vb

Loading data from SQL server into datagridview but Warning 1 Variable 'dtApplicantLists' is used before it has been assigned a value. A null reference exception could result in runtime. green underline at dtApplicantLists.Load(reader)
Any help, please...
Private Function GetList() As DataTable
Dim dtApplicantLists As DataTable
Dim connString As String = ConfigurationManager.ConnectionStrings("dbx").ConnectionString
Using conn As New SqlConnection(connString)
Using cmmd As New SqlCommand("SELECT FirstName, LastName, Gender, ChosenProg, Aggregate FROM dbo.Applicants", conn)
conn.Open()
Dim reader As SqlDataReader = cmmd.ExecuteReader()
dtApplicantLists.Load(reader)
End Using
End Using
Return dtApplicantLists
End Function
You need to call dtApplicantLists = New DataTable - currently it is null (or Nothing in VB).
Using ... End Using Method will guarantee you won't need to worry about warnings like this one you got, as obviously demonstrated in your Code.
Private Function GetList() As DataTable
Dim SqlStr As String =
("SELECT FirstName, LastName, Gender, ChosenProg, Aggregate FROM dbo.Applicants")
Using dtApplicantLists As DataTable = New DataTable
Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("dbx").ConnectionString),
Cmd As New SqlCommand(SqlStr, conn)
conn.Open()
Using Reader As SqlDataReader = Cmd.ExecuteReader
dtApplicantLists.Load(Reader)
End Using
End Using
Return dtApplicantLists
End Using
End Function
You can do it this way.
Imports System.Data.SqlClient
Public Class Form1
Dim connetionString As String
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter
Dim cmdBuilder As SqlCommandBuilder
Dim ds As New DataSet
Dim changes As DataSet
Dim sql As String
Dim i As Int32
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
connection = New SqlConnection(connetionString)
Sql = "select * from Product"
Try
connection.Open()
adapter = New SqlDataAdapter(Sql, connection)
adapter.Fill(ds)
connection.Close()
DataGridView1.Data Source= ds.Tables(0)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Try
cmdBuilder = New SqlCommandBuilder(adapter)
changes = ds.GetChanges()
If changes IsNot Nothing Then
adapter.Update(changes)
End If
MsgBox("Changes Done")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
See the link below for some other similar, but slightly different options.
http://vb.net-informations.com/dataadapter/dataadapter-datagridview-sqlserver.htm

how to insert checked items from checkedlistbox to SQL database?

I am trying to save checked items from a checkedlistbox to my SQL database and i am filling my checkedlistbox from the same SQL database,So far i am able to get the text of checked item from the checkedlistbox and i saved it in a string then i used a label to display if i am getting the text of checked item or not and its working but when i try to insert the checked data in database i get a error "Connection property has not been initialized." on ExecuteNonQuery() method.
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim da As New SqlDataAdapter
Dim dt As New DataTable
Dim connectionString As String = "Server=DESKTOP-V12PTAV ;Database=test ;User Id=sa ;Password=wills8877"
Using conn As New SqlConnection(connectionString)
conn.ConnectionString = connectionString
conn.Open()
Dim str As String
str = "Select sem1 From sem"
da = New SqlDataAdapter(str, conn)
dt = New DataTable
da.Fill(dt)
CheckedListBox1.DataSource = dt
CheckedListBox1.DisplayMember = "sem1"
conn.Close()
End Using
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim str As String
Dim cmd As New SqlCommand
Dim sql As String
Dim connectionString As String = "Server=DESKTOP-V12PTAV ;Database=test ;User Id=sa ;Password=wills8877"
Using conn As New SqlConnection(connectionString)
conn.Open()
Dim itemChecked As Object
For Each itemChecked In CheckedListBox1.CheckedItems
str = itemChecked.item("sem1").ToString
Label1.Text = str
sql = "insert into pretab(pre) values('" + str + "')"
cmd.ExecuteNonQuery()
Next
conn.Close()
End Using
End Sub
End Class
This error
The problem maybe arised from your query syntax. Try this:
sql = "insert into pretab(pre) values(#str)"
cmd.Parameters.AddWithValue("#str", str)
cmd.ExecuteNonQuery()
OOPS.. I just realised that you forgot to assign your command with connection. So, please try to add the following statement:
cmd = New SqlCommand(sql, conn)
befor execution your command. So the final code should look like this:
sql = "insert into pretab(pre) values(#str)"
cmd = New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("#str", str)
cmd.ExecuteNonQuery()
First off I would do data operations in a class e.g. (note I focus on inserts). You need to change server and catalog to your server and catalog on SQL-Server.
Imports System.Data.SqlClient
Public Class Operations
Private Server As String = "KARENS-PC"
Private Catalog As String = "CheckedListBoxDatabase"
Private ConnectionString As String = ""
Public Sub New()
ConnectionString = $"Data Source={Server};Initial Catalog={Catalog};Integrated Security=True"
End Sub
Public Function Read() As DataTable
' read rows for checked listbox here
End Function
Public Sub Insert(ByVal sender As List(Of String))
Using cn As SqlConnection = New SqlConnection With {.ConnectionString = ConnectionString}
Using cmd As SqlCommand = New SqlCommand With {.Connection = cn, .CommandText = "insert into pretab(pre) values (#pre)"}
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#pre", .SqlDbType = SqlDbType.NVarChar})
cn.Open()
For Each item In sender
cmd.Parameters("#pre").Value = item
cmd.ExecuteNonQuery()
Next
End Using
End Using
End Sub
End Class
Form code
Public Class Form1
Private ops As New Operations
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Result = CheckedListBox1.Items.OfType(Of String).Where(Function(item, index) CheckedListBox1.GetItemChecked(index)).ToList
ops.Insert(Result)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
CheckedListBox1.DataSource = ops.Read
CheckedListBox1.DisplayMember = "sem1"
End Sub
End Class
It appears that you did not provide the connection to the command. Your code was button click
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim str As String
Dim cmd As New SqlCommand
Dim sql As String
Dim connectionString As String = "Server=DESKTOP-V12PTAV ;Database=test ;User Id=sa ;Password=wills8877"
Using conn As New SqlConnection(connectionString)
conn.Open()
Dim itemChecked As Object
For Each itemChecked In CheckedListBox1.CheckedItems
str = itemChecked.item("sem1").ToString
Label1.Text = str
sql = "insert into pretab(pre) values('" + str + "')"
cmd.ExecuteNonQuery()
Next
conn.Close()
End Using
End Sub
What you need to do is before cmd.ExecuteNonQuery() you need to provide it a connection cmd.connection = connectionString
this will remove the cmd.ExecuteNonQuery() error.

How to select an excel data Table using a drop downlist value

I am working on an application that uses excel files as its data source. I would love the DataGridView to populate with the columns of a sheet when a worksheet name is selected from the drop down list.
Here is what I have tried doing:
Imports System.Data.OleDb
Public Class Form101
Public cn As New OleDbConnection
Public cm As New OleDbCommand
Public da As OleDbDataAdapter
Dim comb As String
Public dt As New DataTable
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Comb1.SelectedIndexChanged
comb = Comb1.SelectedText
End Sub
Public Sub FillDataGridView(ByVal Query As String)
da = New OleDbDataAdapter(Query, cn)
dt.Clear()
da.Fill(dt)
With DataGridView1
.DataSource = dt
.Columns(0).HeaderText = "Date"
.Columns(1).HeaderText = "Qty brought"
.Columns(2).HeaderText = "Qty sold"
.Columns(3).HeaderText = "Goods balance"
.Columns(1).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
End With
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
cn.ConnectionString = "provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\toojah app\Stock card.xls; Extended Properties= Excel 8.0;"
cn.Open()
FillDataGridView("select * FROM ['" & comb & "'] ")
End Sub
End Class
Try something like this. The first function will collect all of the columns and records in your excel file and place it into a datatable. Then If you wanted to add additional columns to the datable you can do it in the Public Sub CreateDataGridView. This has been tested and works.
Friend Shared Function BuildDatatable () as datatable
Dim dt As New DataTable
Dim Conn As System.Data.OleDb.OleDbConnection
Dim cmd As System.Data.OleDb.OleDbDataAdapter
dim MyFile as string = "C:\toojah app\Stock card.xls"
Conn = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + MyFile + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1';")
Conn.Open()
Dim dtSheets As DataTable = Conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim listSheet As New List(Of String)
Dim drSheet As DataRow
For Each drSheet In dtSheets.Rows
listSheet.Add(drSheet("TABLE_NAME").ToString())
cmd = New System.Data.OleDb.OleDbDataAdapter("select * from [" & drSheet("TABLE_NAME").ToString() & "]", Conn)
cmd.TableMappings.Add("Table", "Net-informations.com")
cmd.Fill(dt)
Conn.Close()
Next
Return dt
Catch ex As Exception
Return Nothing
End Try
End Function
'This is used to pass the function datatable as a dt to then pass to the public sub as shown below.
Dim dt As DataTable = BuildDatatable
Public Sub CreateDataGridView(dt)
Dim newColumn As New Data.DataColumn("ComeColumnName", GetType(System.String))
newColumn.DefaultValue = "YourValues"
dt.Columns.Add(newColumn)
DataGridView1.DataSource = dt
End Sub

Visual Studio: cannot resolve connect identifier

I am able to compile to run the code, but when the form is out and I enter value to be searched, it gives the error stated in the title. This is the code:
Public Class Form1
Private Sub Search_Click(sender As Object, e As EventArgs) Handles Search.Click
Dim myConn As New OleDb.OleDbConnection
Dim myString As String
Dim myArg As String
Dim mysql As String
' Connect to dataset
myString = "Provider=msdaora;data source=orcl;User Id=XXXXXX;Password=XXXXX"
myConn.ConnectionString = myString
' Get the argument
myArg = TextBox1.Text
mysql = "select * from Orders where lastname like '%" + myArg + "%'"
Try
myConn.Open()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
'Create data adapter
Dim myDataadapter As New OleDb.OleDbDataAdapter(mysql, myConn)
' Create a dataset
Dim myDs As New DataSet
' Fill the dataset
myDataadapter.Fill(myDs, "customer")
' Display ADO data.....
DataGridView1.DataSource = myDs
DataGridView1.DataMember = "customer"
End Sub
End Class

Pass DataTable from Class to Main Form

I am stupidly new to VB.. I have my Class (dalv1) where all my functions are stored and my Main Form.
Code is as follows:
Public Sub getCustomerDetails()
Try
Dim cust_dataTable As New DataTable()
Dim Connection As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source = C:\Users\Public\Documents\VP - A1\Database\Database.mdb"
Dim SQL As String = ("SELECT * FROM tblCustomers")
Dim dataAdapter As New OleDbDataAdapter(SQL, Connection)
dataAdapter.Fill(cust_dataTable)
dataAdapter.Dispose()
Catch ex As Exception
MsgBox("ERROR : " & ex.Message.ToString)
End Try
End Sub
I want to pass the DataTable, cust_dataTable to the Main Form so I can populate text boxes when the form loads.
You need to turn it into a function so that the table gets returned to the caller:
Public Function getCustomerDetails() As DataTable
Dim cust_dataTable As New DataTable()
Try
Dim Connection As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source = C:\Users\Public\Documents\VP - A1\Database\Database.mdb"
Dim SQL As String = ("SELECT * FROM tblCustomers")
Dim dataAdapter As New OleDbDataAdapter(SQL, Connection)
dataAdapter.Fill(cust_dataTable)
dataAdapter.Dispose()
Catch ex As Exception
MsgBox("ERROR : " & ex.Message.ToString)
End Try
Return cust_dataTable
End Function
You didn't share your form's code, but here is an example of how you would call it:
Private da As New dalv1
Private _MyDataTable As DataTable
Protected Overrides Sub OnLoad(ByVal e As EventArgs)
MyBase.OnLoad(e)
_MyDataTable = da.getCustomerDetails
End Sub