From Data Set to Textbox in VB.Net using MS-Access - vb.net

Private Function Gelobee() As DataSet
Dim connection As OleDb.OleDbConnection = New OleDbConnection
connection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=CMP.accdb"
connection.Open()
Dim da As OleDb.OleDbDataAdapter = New OleDbDataAdapter("SELECT IDDesc FROM [ItemDesc] WHERE " & PartNoTxt.Text & " ORDER BY IDID;", connection)
Dim ds As New DataSet
da.Fill(ds, "FilteredDesc")
Return ds
connection.Dispose()
connection = Nothing
DescTxt.Text = ds.Tables(0).Rows(1).Item(1)
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Gelobee()
End Sub
I am trying to get the result of the query in Function Gelobee to go to DescTxt.Text when I click the Button1. When I click the Button1, nothing appears in the DescTxt. No errors but It wont show the result in the textbox.

Your code stops at the Return statement.
Change Gelobee() to this:
Private Function Gelobee() As DataSet
... ' Removed for brevity
da.Fill(ds, "FilteredDesc")
connection.Dispose()
connection = Nothing
DescTxt.Text = ds.Tables(0).Rows(1).Item(1)
Return ds
End Function

Related

How can I make a datagridview live connected to an access database stored locally in VB.NET?

I would like it so when I delete/edit a record from the datagridview, it will automatically delete/edit the access database file. Here is a snippet of my code which loads the database into the datagridview.
Public Function dbConnect() As Boolean
Try
cn = New OleDbConnection(DataBasePath)
cn.Open()
'MessageBox.Show("is work ")
Return True
Catch ex As Exception
MessageBox.Show("Unable to open the database: " & ex.Message)
Return False
End Try
End Function
Private Function GetOrders() As DataTable
Dim dtOrders As New DataTable
dbConnect()
Dim SQLCMD As New OleDbCommand
SQLCMD.Connection = cn
SQLCMD.CommandText = "Select * From [OrdersTbl]"
dtOrders.Load(SQLCMD.ExecuteReader())
Return dtOrders
End Function
Private Sub EditOrdersForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
OrdersDataGrid.DataSource = GetOrders()
End Sub
How can I make it so that changes are saved to the local file.
I have a datagridview and a button on the form. Here's the code you can refer to:
Private dt As DataTable = New DataTable
Private da As OleDbDataAdapter
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim connection As OleDbConnection = New OleDbConnection("your connection string")
connection.Open()
Dim cmdTxt As String = "SELECT * FROM yourTable"
da = New OleDbDataAdapter(New OleDbCommand(cmdTxt, connection))
Dim builder As OleDbCommandBuilder = New OleDbCommandBuilder(da)
da.Fill(dt)
Dim source As BindingSource = New BindingSource With {
.DataSource = dt
}
DataGridView1.DataSource = source
connection.Close()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
DataGridView1.EndEdit()
da.Update(dt)
End Sub
Every time you want to update database from your datagridview, just click the button.

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.

VB.Net SQL Count Statement into a label

I'm trying to count the students whose teacher where teacher = '" & lblTeacher.Text & "'"
EXAMPLE :
Public Class Form1
Dim conn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Richard\Desktop\Dbase.mdb"
Dim con As New OleDbConnection
Dim da, da1 As New OleDbDataAdapter
Dim dt, dt1 As New DataTable
Dim sql As String
Dim ds As New DataSet
Public Sub display()
sql = "select * from Info"
dt.Clear()
con.Open()
da = New OleDbDataAdapter(sql, con)
da.Fill(dt)
con.Close()
DataGridView1.DataSource = dt.DefaultView
End Sub
Public Sub count()
sql = "select COUNT(name) from Info where teacher = '" & lblTeacher.Text & "'"
da1 = New OleDbDataAdapter(sql, con)
ds.Clear()
con.Open()
da.Fill(ds)
lblCount.Text = ds.Tables(0).Rows.Count.ToString
con.Close()
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
con.ConnectionString = conn
display()
End Sub
Private Sub DataGridView1_Click(sender As System.Object, e As System.EventArgs) Handles DataGridView1.Click
lblTeacher.Text = DataGridView1.CurrentRow.Cells("teacher").Value.ToString
count()
End Sub
End Class
1:
Try this instead of your current count() method. Pay special attention to my comments; they address some poor practices from the original code:
' Better functional style: accept a value, return the result
Public Function GetStudentCount(teacher As String) As Integer
'**NEVER** use string concatenation to put data into an SQL command!!!
Const sql As String = "select COUNT(name) from Info where teacher = ?"
'Don't try to re-use the same connection in your app.
' It creates a bottleneck, and breaks ADO.Net's built-in connection pooling,
' meaning it's more likely to make object use *worse*, rather than better.
'Additionally, connection objects should be created in a Using block,
' so they will still be closed if an exception is thrown.
' The original code would have left the connection hanging open.
Using con As New OleDbConnection(conn), _
cmd As New OleDbCommand(sql, con)
'This, rather than string concatenation, is how you should put a value into your sql command
'Note that this NEVER directly replaces the "?" character with the parameter value,
' even in the database itself. The command and the data are always kept separated.
cmd.Parameters.Add("teacher", OleDbType.VarChar).Value = teacher
con.Open()
' No need to fill a whole dataset, just to get one integer back
Return DirectCast(cmd.ExecuteScalar(), Integer)
'No need to call con.Close() manually. The Using block takes care of it for you.
End Using
End Function
Here it is again, without all the extra comments:
Public Function GetStudentCount(teacher As String) As Integer
Const sql As String = "select COUNT(name) from Info where teacher = ?"
Using con As New OleDbConnection(conn), _
cmd As New OleDbCommand(sql, con)
cmd.Parameters.Add("teacher", OleDbType.VarChar).Value = teacher
con.Open()
Return DirectCast(cmd.ExecuteScalar(), Integer)
End Using
End Function
Call it like this:
Private Sub DataGridView1_Click(sender As System.Object, e As System.EventArgs) Handles DataGridView1.Click
lblTeacher.Text = DataGridView1.CurrentRow.Cells("teacher").Value.ToString()
lblCount.Text = GetStudentCount(lblTeacher.Text).ToString()
End Sub

Invalid Operation Exception when filling DataSet

The is a database driven currency converter, where the program has to fetch the exchange rates from the database and display them.
This is what I've done so far.
Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker1.ValueChanged
Dim da As OleDb.OleDbDataAdapter
Dim ds As New DataSet
Dim sql As String
sql = "SELECT TOP 1 USD,EUR,GBP FROM dbexchangeRates WHERE Date='" & DateTimePicker1.Text.ToString & "'"
da = New OleDb.OleDbDataAdapter(sql, cnnOLEDB)
da.Fill(ds, "rates")
If ds.Tables("rates").Rows.Count > 0 Then
txtUSD.Text = ds.Tables("rates").Rows(0).Item(0).ToString
txtGBP.Text = ds.Tables("rates").Rows(0).Item(1).ToString
txtEUR.Text = ds.Tables("rates").Rows(0).Item(2).ToString
End If
End Sub
End Class
I recieve an Invalid operation exception on the
a.Fill(ds, "rates") '
What am i doing wrong?
Thank you for your time.
Try this:
Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker1.ValueChanged
Dim ds As New DataSet
Dim sql As String = "SELECT TOP 1 USD,EUR,GBP FROM dbexchangeRates WHERE Date= ?"
Using connection As New OleDb.OleDbConnection(strConnectionString),
command As New OleDb.OleDbCommand(sql, connection),
adapter As New OleDb.OleDbDataAdapter(command)
connection.Open()
adapter.SelectCommand.Parameters.Add("#dt", OleDb.OleDbType.Date).Value = DateTimePicker1.Value
adapter.Fill(ds, "rates")
connection.Close()
End Using
If ds.Tables("rates").Rows.Count > 0 Then
txtUSD.Text = ds.Tables("rates").Rows(0).Item(0).ToString
txtGBP.Text = ds.Tables("rates").Rows(0).Item(1).ToString
txtEUR.Text = ds.Tables("rates").Rows(0).Item(2).ToString
End If
End Sub
I haven't checked but I wonder if the method DateTimePicker1.ValueChanged is being called before cnnOLEDB has been initialised on MyBase.Load. This way the connection, command and adapter are all initialised at the same time. By implementing Using they will also be disposed.
You probably also want to do some data validation to ensure a valid date is set before calling the database with a query otherwise other exceptions could occur.

How To Populate a DropDown List From a DataSet?

I am trying to populate an ASP dropdown list in vb.net with the results from a stored procedure returned in a data set. I was wondering if anyone knew the vb.net code to populate the dropdown list?
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim connString As String = "Server=MYCOMPUTER\SQLEXPRESS;Database=scales;Trusted_Connection=True"
Dim myConn As New SqlConnection(connString)
myConn.Open()
Dim da As New SqlDataAdapter("select scaleName from scales", myConn)
Dim dt As New DataTable
da.Fill(dt)
ComboBox1.DisplayMember = "scaleName"
ComboBox1.DataSource = dt
myConn.Close()
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
IF Not IsPostback then
PopulateDropdown()
End IF
End Sub
Private Sub PopulateDropDown()
Dim connString As String = "Server=MYCOMPUTER\SQLEXPRESS;Database=scales;Trusted_Connection=True"
Dim myConn As New SqlConnection(connString)
myConn.Open()
Dim da As New SqlDataAdapter("select ScaleId, scaleName from scales", myConn)
Dim dt As New DataTable
da.Fill(dt)
Me.ComboBox1.DataTextField = "scaleName "
Me.ComboBox1.DataValueField = "ScaleId"
Me.ComboBox1.DataSource = dt
Me.ComboBox1.DataSourceID = String.Empty
Me.ComboBox1.DataBind()
myConn.Close()
End Sub
In order to show the data in the DropDownList control, you can use the following Code. To use the results of a Stored Procedure, you need to create the SELECT command:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim dt As New DataTable
Dim connString As String = "Server=MYCOMPUTER\SQLEXPRESS;Database=scales;Trusted_Connection=True"
Using myConn As New SqlConnection(connString)
myConn.Open()
Using cmd = myConn.CreateCommand()
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "dbo.uspMyStoredProc"
cmd.Parameters.AddWithValue("#MyInputParam", 123)
Using da As New SqlDataAdapter(cmd)
da.Fill(dt)
End Using
End Using
End Using
ComboBox1.DisplayMember = "scaleName"
ComboBox1.DataSource = dt
ComboBox1.DataBind()
End If
' ...
End Sub
I've adjusted the following things:
Usually you only need to bind the data on the initial request. Therefore, the if statement at the beginning checks the IsPostBack property.
In order to close and dispose the connection and the data datapter reliably, I've added some using statements.
In order to access the stored procedure, I've created a SqlCommand and set the CommandType to StoredProcedure. The CommandText is set to the name of the Stored Procedure. In the sample, I've also added a parameter named MyInputParam that is sent to the Stored Procedure.