returning select value using Visual Basic 2010 oleDB - vb.net

I'm trying to read a excel cell with visual basic 2010 ( I'm really new to this) and I think I finally did it BUT I have no clue how to return the result.
It should end up in the clipboard or msgBox from there I'll find my way :D
I searched for two hours now but didnt find the solution... please help me
Thanks
Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click
cn.ConnectionString = "provider=microsoft.jet.oledb.4.0;data source=C:\Users\marcelf\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsApplication1\bin\Debug\DB.xls;extended properties=excel 8.0;"
cn.Open()
With cm
.Connection = cn
.CommandText = "SELECT * FROM [ccs$C1:B20] WHERE 'id' = 'German'"
.ExecuteNonQuery()
End With
cn.Close()
MsgBox(????)
End Sub
EDIT: her is the updated code. I get "Could not find installable ISAM
Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click
Dim con As New OleDbConnection
Try
Using con
'added HDR=No to the extended properties of the connection string
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;data source=C:\Users\marcelf\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsApplicat'ion1\bin\Debug\DB.xls;extended properties=excel 12.0;HDR=Yes"
con.Open()
Using cmd = New OleDbCommand
cmd.Connection = con
cmd.CommandText = "SELECT * FROM [ccs$C1:C20] WHERE 'id' = 'German'"
Using oRDR As OleDbDataReader = cmd.ExecuteReader
While (oRDR.Read)
MsgBox(oRDR.GetValue(0)) 'gets the first returned column
End While
End Using
con.Close()
End Using
End Using
Catch ex As Exception
Throw New Exception(ex.Message)
Finally
con.Close()
End Try
End Sub
EDIT: That's what worked for me:
Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click
Dim con As New OleDbConnection
Try
Using con
'added HDR=No to the extended properties of the connection string
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\marcelf\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsApplication1\bin\Debug\DB.xls;Mode=3;User ID=Admin;Password=;Extended Properties=Excel 8.0"
con.Open()
Using cmd = New OleDbCommand
cmd.Connection = con
cmd.CommandText = "SELECT Service FROM [ccs$] WHERE id='" & ComboBox1.SelectedItem & "'"
Using oRDR As OleDbDataReader = cmd.ExecuteReader
While (oRDR.Read)
MsgBox(oRDR.GetValue(0)) 'gets the first returned column
End While
End Using
con.Close()
End Using
End Using
Catch ex As Exception
Throw New Exception(ex.Message)
Finally
con.Close()
End Try
End Sub

Welcome to SO. In the future you should show us all of your code. Since you tagged OleDB and vb.net, the following implements what you are trying to accomplish. I included the Form Class so the Imports statements could be shown, but you can just copy and paste the click event code after insuring you Class includes the Imports. Note, I have not tested this code but it should work. Let me know if you need clarification or additional help.
Imports System.Data.OleDb
Public Class Form1
Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click
Dim con As New OleDbConnection
Try
Using con
'added HDR=No to the extended properties of the connection string
' **EDIT**
con.ConnectionString = "Provider=Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\marcelf\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsApplicat'ion1\bin\Debug\DB.xls;Mode=3;User ID=Admin;Password=;Extended Properties=Excel 8.0"
con.Open()
Using cmd = New OleDbCommand
cmd.Connection = con
cmd.CommandText = "SELECT * FROM [ccs$C1:B20] WHERE 'id' = 'German'"
Using oRDR As OleDbDataReader = cmd.ExecuteReader
While (oRDR.Read)
MsgBox(oRDR.GetValue(0)) 'gets the first returned column
End While
End Using
con.Close()
End Using
End Using
Catch ex As Exception
Throw New Exception(ex.Message)
Finally
con.Close()
End Try
End Sub
End Class

Related

where should i put the button save codes into this codes that i sent here? because i'd like to save into another table

i put this code because i used combobox and they fill my two textbox,but when try to save its not saving the data that i put
this is the code
Sub loaddata()
Try
reload("SELECT * FROM NAME", STUDENT)
STUDENT.DataSource = dt
STUDENT.DisplayMember = "NAME"
STUDENT.ValueMember = "ID"
Catch ex As Exception
End Try
End Sub
Private Sub NAME_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NAME.SelectedIndexChanged
Try
Dim sql As String
Dim cmd As New OleDbCommand
Dim dt As New DataTable
Dim da As New OleDbDataAdapter
strcon.Open()
sql = "SELECT * FROM STUDENT where NAME LIKE '%" & NAME.Text & "%'"
cmd.Connection = strcon
cmd.CommandText = sql
da.SelectCommand = cmd
da.Fill(dt)
If dt.Rows.Count > 0 Then
GENDER.Text = dt.Rows(0).Item("GENDER").ToString
ADDRESS.Text = dt.Rows(0).Item(" ADDRESS").ToString
End If
Catch ex As Exception
Finally
strcon.Close()
End Try
End Sub
please show me how to put the save codes here,because i use only the BindingNavigator1 to save, but it does not save, sorry if my grammar is wrong because i'm not a fluent in english
I know we have a language barrier but we are both trying our best. I have provided a few examples of code to interact with a database.
It is a good idea to keep you database code separate from you user interface code. If you want to show a message box in you Try code, keep the Try in the user interface code. The error will bubble up from the database code to the calling code.
Using...End Using blocks take care of disposing of database objects. Parameters protect against Sql injection because parameter values are not considered executable code by the database. Note that for OleDb data sources the order that the parameters appear in the sql statement must match the order that they are added to the Parameters collection.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Dim dt = GetOriginalData()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
ComboBox1.DisplayMember = "Name"
ComboBox1.ValueMember = "ID"
ComboBox1.DataSource = dt
End Sub
Private Function GetOriginalData() As DataTable
Dim dt As New DataTable
Using cn As New OleDbConnection("Your first connection string"),
cmd As New OleDbCommand("Select ID, Name From Table1;")
cn.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
InsertData(CInt(ComboBox1.SelectedValue), ComboBox1.SelectedText, txtGender.Text, txtAddress.Text)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub InsertData(id As Integer, name As String, gender As String, address As String)
Using cn As New OleDbConnection("Your second connection string"),
cmd As New OleDbCommand("Insert Into Table2 (ID, Name, Gender, Address) Values (#ID, #Name, #Gender, #Address);", cn)
With cmd.Parameters
.Add("#ID", OleDbType.Integer).Value = id
.Add("#Name", OleDbType.VarChar).Value = name
.Add("#Gender", OleDbType.VarChar).Value = gender
.Add("#Address", OleDbType.VarChar).Value = address
End With
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub

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

“syntax error in INSERT INTO statement”

I'm a beginner in vb.net
I've got the following Error upon executing the Insert-Statement
syntax error in INSERT INTO statement
Here is my code:
Private Sub cmdadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdadd.Click
Try
Dim sql As String = " INSERT INTO [Login1] ([ID],[Username],[Password])" & _
" VALUES(?,?,?)"
Dim cmd As New OleDbCommand
With cmd
.Connection = con
.CommandText = sql
.Parameters.AddWithValue("?", txtid)
.Parameters.AddWithValue("?", txtuser)
.Parameters.AddWithValue("?", txtpass)
.ExecuteNonQuery()
End With
MsgBox("The Data Has Been Added")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Could anyone help me?
Try to use sql parameter names
Private Sub cmdadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdadd.Click
Try
Dim sql As String = " INSERT INTO [Login1] ([ID],[Username],[Password])" & _
" VALUES(#ID,#Username,#Password)"
Dim cmd As New OleDbCommand
With cmd
.Connection = con
.CommandText = sql
.Parameters.AddWithValue("#ID", txtid)
.Parameters.AddWithValue("#Username", txtuser)
.Parameters.AddWithValue("#Password", txtpass)
.Open()
.ExecuteNonQuery()
.Close()
End With
MsgBox("The Data Has Been Added")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Note that: You should properly close your connections after you use them. Therefore following code may be better.
Private Sub InsertLogin()
Dim sql As String = " INSERT INTO [Login1] ([ID],[Username],[Password])" & _
" VALUES(#ID,#Username,#Password)"
Using con As New OleDbConnection(ConnectionStringHERE)
Using cmd As New OleDbCommand
Dim cmd As New OleDbCommand
cmd.Connection = con
cmd.CommandText = sql
cmd.Parameters.AddWithValue("#ID", txtid)
cmd.Parameters.AddWithValue("#Username", txtuser)
cmd.Parameters.AddWithValue("#Password", txtpass)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End Sub
Private Sub cmdadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdadd.Click
Try
InsertLogin()
MsgBox("The Data Has Been Added")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Here, I used cmd. syntax, it is no different then using With.
You have to name the sql parameters.
Look at the examples in the documentation: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue%28v=vs.110%29.aspx

Data updation and deletion error

I have a DataGrid and many text fields to add data into the database. When i add a new data, it gets updated in the database and in the data grid.But when i delete the data, it gets deleted only from the database. It doesn't get updated in the data grid.
When i try to update the data, it updates only one record at a time.when i try for another record it gives me a error "The variable name '#date' has already been declared. Variable names must be unique within a query batch or stored procedure." I have to close and reopen the form to update a new record.
Imports System.Data.SqlClient
Public Class Form
Dim con As New SqlClient.SqlConnection("Server = DEL-PC; Database=Shj; Trusted_Connection=yes;")
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
Dim ds As DataSet
Dim da As SqlDataAdapter
Private Sub Form_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SqlDataAdapter1.Fill(DataSet11)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles newbtn.Click
If RegNoTextBox.Text <> "" Then
cmd.Connection = con
con.Open()
cmd.CommandText = "insert into WaterProofing(Date,RegNo) values ('" & DateDateTimePicker.Value & "','" & RegNoTextBox.Text & "')"
cmd.ExecuteNonQuery()
Call showdata()
con.Close()
Else
MessageBox.Show("Please enter registration number")
End If
End Sub
//updation
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles editbtn.Click
cmd.Parameters.AddWithValue("#date", DateDateTimePicker.Value)
cmd.Parameters.AddWithValue("#regno", RegNoTextBox.Text)
cmd.Connection = con
con.Open()
cmd.CommandText = "update WaterProofing set RegNo= #regno where date=#date"
cmd.ExecuteNonQuery()
Call showdata()
con.Close()
MessageBox.Show("Details Updated!")
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles deletebtn.Click
cmd.Connection = con
con.Open()
cmd.CommandText = "delete from WaterProofing where date='" & DateDateTimePicker.Value & "'"
cmd.ExecuteNonQuery()
Call showdata()
con.Close()
MessageBox.Show("Details Deleted!")
End Sub
Sub showdata()
SqlDataAdapter1.Fill(DataSet11, "WaterProofing")
With DataGridView
.Update()
End With
End Sub
End Class
Please help me in deletion and updating.
You're adding parameters before declaring CommandText at Button2_Click
Try it in this way:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles editbtn.Click
Try
Dim command As New SqlCommand
con.Open()
command.Connection = con
command.CommandText = "update WaterProofing set RegNo= #regno where date=#date"
command.Parameters.AddWithValue("#date", DateDateTimePicker.Value)
command.Parameters.AddWithValue("#regno", RegNoTextBox.Text)
command.ExecuteNonQuery()
con.Close()
Call showdata()
MessageBox.Show("Details Updated!")
Catch ex as Exception
MessageBox.Show(ex.Message)
End try
End Sub
UPDATE
Basically you have to do the same thing when you load the DataGridView for the first time in order to refresh the DataGridView with the current data from database after deleting or updating records, so your ShowData Sub might look something like this
Private Sub ShowData()
Dim Connection As SqlConnection
Connection = New SqlConnection("YourConnectionString")
Try
Connection.Open()
Dim SQL As String = "SELECT Field1, Field2, Field3 FROM Table"
Dim DS As New DataSet
Dim Adapter As New SqlDataAdapter(SQL, Connection)
Adapter.Fill(DS)
DataGridView.DataSource = DS.Tables(0)
DataGridView.Refresh()
Catch ex As Exception
MessageBox(ex.Message)
Finally
Connection.Close()
End Try
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles deletebtn.Click
Try
Dim command As New SqlCommand
con.Open()
command.Connection = con
command.CommandText = "delete from WaterProofing where date='" & DateDateTimePicker.Value & "'"
command.ExecuteNonQuery()
con.Close()
Call ShowData_Delete()
MessageBox.Show("Details Deleted!")
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
End Try
End Sub
Private Sub ShowData_Delete()
Dim Connection As SqlConnection
Try
Connection = New SqlConnection("Server = DEL-PC; Database=Shj; Trusted_Connection=yes;")
Connection.Open()
Dim SQL As String = "SELECT * from WaterProofing"
Dim DS As New DataSet
Dim Adapter As New SqlDataAdapter(SQL, Connection)
Adapter.Fill(DS)
DataGridView1.DataSource = DS.Tables(0)
DataGridView1.Refresh()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
Connection.Close()
End Try
End Sub

adding a value to my combo box using query

I'm trying to populate my combo box using the information in my database.. but I don't know the code for populating it. btw, I'm using vb windows form.
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim con As SqlConnection = New SqlConnection("Data Source=PC11-PC\kim;Initial Catalog=Acounting;User ID=sa;Password=123")
Dim cmd As SqlCommand = New SqlCommand("select distinct CompanyName from company ", con)
cmd.ExecuteReader()
con.Open()
While cmd.ExecuteReader.Read
End While
con.Close()
End Sub
Private Sub Form1_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Using cnn As New SqlConnection("Data Source=PC11-PC\kim;Initial Catalog=Acounting;User ID=sa;Password=123")
Using Adp as new SqlDataAdapter("select distinct CompanyName from company", con)
Dim Dt as New DataTable
Adp.Fill(Dt)
ComboBox1.DataSource=Dt
ComboBox1.DisplayMember="CompanyName"
End Using
End Using
End Sub
Using cnn As New SqlConnection("Data Source=PC11-PC\kim;Initial Catalog=Acounting;User ID=sa;Password=123")
Using cmd As New SqlCommand("select distinct CompanyName from company", cnn)
Try
cnn.Open()
Dim r = cmd.ExecuteReader
If r.HasRows Then
While r.Read
''add the items to the ComboBox
ComboBox1.Items.Add(r.GetString(0))
End While
End If
Catch ex As Exception
''handle the error
End Try
End Using
End Using