How to Insert new row to Access database - vb.net

Beginer question....learning to use ADO.net
I am trying to insert a value to the database but I am having difficulty with the syntax...Trying this code :
Protected Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim connstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Z:\CompanyData.mdb"
Using conn = New OleDbConnection(connstring)
conn.Open()
Dim CieName As String
CieName = txtCieName.Text
Dim sqlQry As String = "INSERT INTO Company (CompanyName) VALUES (#CieName)"
Using cmd As New OleDbCommand(sqlQry, conn)
cmd.Parameters.AddWithValue("#CieName", CieName)
cmd.ExecuteNonQuery()
End Using
End Using
End Sub
is #CieName legal for an Access Database ?

Related

count of rows in MS access database in vb.net

Does anyone know what is wrong?
I am trying to count number of rows in MS access Database.
Here is code which I tried:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim conn As New OleDbConnection
conn.ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Test Database\Database.accdb")
conn.Open()
Dim strsql As String
strsql = "Select count(*) from TABLA" '" select Panel from PANELS where ID"
Dim cmd As New OleDbCommand(strsql, conn)
Dim myreader As OleDbDataReader
myreader = cmd.ExecuteReader
myreader.Read()
PanelsInDatabase = myreader.Item(strsql)
Label1.Text = PanelsInDatabase
conn.Close()
For i As Integer = 0 To PanelsInDatabase - 1
CreatePanels()
CreateDeleteButton(_PanelName)
CreateLabels(_PanelName)
CreateLabel2(_PanelName)
Next
End Sub
if I start code, I get an error:
System.IndexOutOFRangeException
I have separated you user interface code from your database code. Of course, I don't know what CreatePanels is doing or where _PanelName is coming from. In your UI code you call the GetTABLACount function which returns as Integer.
In the database code use Using...End Using blocks for the connection and command so they are properly disposed even if there is an error.
Since you are only retrieving a single piece of data, you can use .ExecuteScalar which returns the first column of the first row of the result set As Object. Use CInt to get the Integer.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim count = GetTABLACount()
Label1.Text = count.ToString
For i As Integer = 0 To count - 1
CreatePanels()
CreateDeleteButton(_PanelName)
CreateLabels(_PanelName)
CreateLabel2(_PanelName)
Next
End Sub
Private Function GetTABLACount() As Integer
Dim dbCount As Integer
Using conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Test Database\Database.accdb"),
cmd As New OleDbCommand("Select count(*) from TABLA", conn)
conn.Open()
dbCount = CInt(cmd.ExecuteScalar)
End Using
Return dbCount
End Function
Use ExecuteScalar when you are selecting a single value
Dim connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Test Database\Database.accdb"
Dim sql = "select count(*) from tabla"
Using cmd As New OleDbCommand(sql, New OleDbConnection(connStr))
cmd.Connection.Open()
Dim ct = CInt(cmd.ExecuteScalar())
End Using

How to display multiple results from a users' input from filters using MS Access and Visual Basic

I'm struggling to grasp VB as I'm new to programming. I am creating a program which displays a result (namely a link to a website) based on a users' filters. I've done this so far, which just selects the size filter. However, I don't know how to write the code that will check the database for the users' preference and output an appropriate link in the form of a label. Is it as simple as just printing DataTable or am I totally wrong? Any help would be greatly appreciated.
Here is my code so far:
Imports System.Data.OleDb
Public Class frmFilters
Dim provider As String
Dim dataFile As String
Dim ConnString As String
Dim myConnection As OleDbConnection = New OleDbConnection
Private ConStr As String = "My Connection String"
Private Sub buttonSearch_Click(sender As Object, e As EventArgs) Handles buttonSearch.Click
provider = "Provider = Microsoft.ACE.OLEDB.12.0;Data Source="
dataFile = "H:\Visual studio files\Project\CMPC\partLists.accdb"
End Sub
Private Function GetPartData(filterMicroATX As Integer, filterATX As Integer) As DataTable
Dim dt As New DataTable
Dim sql = "SELECT * FROM partList WHERE
[size] > #MicroATX
And [size] < #ATX;"
Using con As New OleDbConnection(ConStr),
cmd As New OleDbCommand(sql, con)
With cmd.Parameters
.Add("#MicroATX", OleDbType.Integer).Value = filterMicroATX
.Add("#ATX", OleDbType.Integer).Value = filterATX
End With
con.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
Private Sub btnQuit_Click(sender As Object, e As EventArgs) Handles btnQuit.Click
Me.Close()
End Sub
End Class

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 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.