Splitting data from database to 3 comboboxes - vb.net

Hello there I wanted to ask if could you split to split data from my database and populate three textboxes. I have a column in my database called DOB (date of birth) its a Varchar I wanted to populate three combo boxes with the data from that column.The code is in the navigaterecord subprocedure. This is my code :
Imports System.Data.SQLite
Public Class Form1
Dim inc As Integer
Dim MaxRows As Integer
Dim ConnectionString As String = "Data Source=dbRoomBookings.db"
Dim ds As New DataSet
Dim dt As New DataTable
Dim mSQL As String = "SELECT * FROM Customer"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New SQLiteConnection(ConnectionString)
Dim cmd As New SQLiteCommand(mSQL, con)
con.Open()
Dim da As New SQLiteDataAdapter(cmd)
da.Fill(ds, "customer")
dt = ds.Tables(0)
MaxRows = ds.Tables("customer").Rows.Count
con.Close()
Dim msSQL As String = "SELECT * FROM customer;"
dgvSearchResults.DataSource = display(msSQL, "customer")
MaxRows = ds.Tables("customer").Rows.Count
inc = -1
End Sub
Private Sub BtnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
If inc <> MaxRows - 1 Then
inc = inc + 1
navigaterecords()
Else
MsgBox("no more rows")
End If
End Sub
Sub navigaterecords()
txtCusId.Text = ds.Tables("customer").Rows(inc).Item(0)
txtFname.Text = ds.Tables("customer").Rows(inc).Item(1)
txtLname.Text = ds.Tables("customer").Rows(inc).Item(2)
cboDay.Text = ds.Tables("customer").Rows(inc).Item(3)
cboMonth.Text = ds.Tables("customer").Rows(inc).Item(3) Then
cboYear.Text = ds.Tables("customer").Rows(inc).Item(3)
txtDbo.Text = ds.Tables("customer").Rows(inc).Item(3) & "/" & ds.Tables("customer").Rows(inc).Item(3) & "/" & ds.Tables("customer").Rows(inc).Item(3)
End Sub
Private Sub BtnPrevious_Click(sender As Object, e As EventArgs) Handles btnPrevious.Click
If inc > 0 Then
inc = inc - 1
navigaterecords()
Else
MsgBox("no more rows")
End If
End Sub
Private Sub BtnFirst_Click(sender As Object, e As EventArgs) Handles btnFirst.Click
If inc <> 0 Then
inc = 0
navigaterecords()
End If
End Sub
Private Sub BtnLast_Click(sender As Object, e As EventArgs) Handles btnLast.Click
If inc <> MaxRows - 1 Then
inc = MaxRows - 1
navigaterecords()
Else
End If
End Sub

Related

Asset Dataset Button

I have been trying to write a program for a company that I work for, that would do assist tracking as well as give an overview of where the assists are.
The idea is to have a database with unique numbers on them that is allocated to all the hardware.
When a "desk" button is pressed it will show the info form that desk and it can be edited from there.
I roughly have what I was looking for, but I'm struggling with an issue when I update data, the data is somehow placed in the incorrect row...
E.g:
Desk Name : TL1
PC : 0001
monitor : 0002
Desk Name : TL2
PC : 0003
monitor : 0004
If I update the fist data entry alone it works fine.. however when I update the second entry it gets saved onto the first entry
E.g:
Desk Name : TL2
PC : 0003
monitor : 0004
Desk Name : TL2
PC : 0003
monitor : 0004
This is the code I have so far, any help would be very appreciated.
Public Class Form1
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Dim MaxRows As Integer
Dim inc As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Lib_9th_NLDataSet.tblContacts' table. You can move, or remove it, as needed.
Me.TblContactsTableAdapter.Fill(Me.Lib_9th_NLDataSet.tblContacts)
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = \\elite03\IT\Assets\Lib 9th NL.mdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "SELECT Desk,Pc,Monitor,Keyboard,Phone,Laptop FROM tblcontacts"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "Lib_9th_NL")
con.Close()
MaxRows = Lib_9th_NLDataSet.tblContacts.Rows(inc).Item(inc)
inc = 0
End Sub
Private Sub NavigateRecords()
txtDesk_Name.Text = ds.Tables("Lib_9th_NL").Rows(inc).Item(0)
txtPC.Text = ds.Tables("Lib_9th_NL").Rows(inc).Item(1)
txtMonintor.Text = ds.Tables("Lib_9th_NL").Rows(inc).Item(2)
txtKeyboard.Text = ds.Tables("Lib_9th_NL").Rows(inc).Item(3)
txtPhone.Text = ds.Tables("Lib_9th_NL").Rows(inc).Item(4)
txtlaptop.Text = ds.Tables("Lib_9th_NL").Rows(inc).Item(5)
End Sub
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Me.Validate()
Me.TblContactsBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.Lib_9th_NLDataSet)
End Sub
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
If inc <> MaxRows - 0 Then
inc = inc + 1
NavigateRecords()
Else
MsgBox("No More Rows")
End If
End Sub
Private Sub btnPrevious_Click(sender As Object, e As EventArgs) Handles btnPrevious.Click
If inc > 0 Then
inc = inc - 1
NavigateRecords()
Else
MsgBox("First Record")
End If
End Sub
Private Sub btnAddNew_Click(sender As Object, e As EventArgs) Handles btnAddNew.Click
btnCommit.Enabled = True
btnUpdate.Enabled = False
btnDelete.Enabled = False
btnAddNew.Enabled = False
txtDesk_Name.Clear()
txtPC.Clear()
txtMonintor.Clear()
txtKeyboard.Clear()
txtPhone.Clear()
txtlaptop.Clear()
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
btnCommit.Enabled = False
btnAddNew.Enabled = True
btnUpdate.Enabled = True
btnDelete.Enabled = True
inc = 0
NavigateRecords()
End Sub
Private Sub btnCommit_Click(sender As Object, e As EventArgs) Handles btnCommit.Click
If inc <> -1 Then
Dim cb As New OleDb.OleDbCommandBuilder(da)
Dim dsNewRow As DataRow
dsNewRow = ds.Tables("Lib_9th_NL").NewRow()
dsNewRow.Item("desk") = txtDesk_Name.Text
dsNewRow.Item("PC") = txtPC.Text
dsNewRow.Item("Monitor") = txtMonintor.Text
dsNewRow.Item("Keyboard") = txtKeyboard.Text
dsNewRow.Item("Phone") = txtPhone.Text
dsNewRow.Item("Laptop") = txtlaptop.Text
ds.Tables("Lib_9th_NL").Rows.Add(dsNewRow)
da.Update(ds, "Lib_9th_NL")
MsgBox("New Record added to the Database")
btnCommit.Enabled = False
btnAddNew.Enabled = True
btnUpdate.Enabled = True >
btnDelete.Enabled = True
End If
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
If MessageBox.Show("Do you really want to Delete this Record?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = DialogResult.No Then
MsgBox("Operation Cancelled")
Exit Sub
End If
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Tables("Lib_9th_NL").Rows(inc).Delete()
MaxRows = MaxRows - 1
inc = 0
da.Update(ds, "Lib_9th_NL")
NavigateRecords()
End Sub
Private Sub TL1_Click(sender As Object, e As EventArgs) Handles TL1.Click
txtDesk_Name.Text = Lib_9th_NLDataSet.tblContacts.Rows(0).Item(1)
txtPC.Text = Lib_9th_NLDataSet.tblContacts.Rows(0).Item(2)
txtMonintor.Text = Lib_9th_NLDataSet.tblContacts.Rows(0).Item(3)
txtKeyboard.Text = Lib_9th_NLDataSet.tblContacts.Rows(0).Item(4)
txtPhone.Text = Lib_9th_NLDataSet.tblContacts.Rows(0).Item(5)
txtlaptop.Text = Lib_9th_NLDataSet.tblContacts.Rows(0).Item(6)
End Sub
Private Sub Ret1_Click(sender As Object, e As EventArgs) Handles Ret1.Click
txtDesk_Name.Text = Lib_9th_NLDataSet.tblContacts.Rows(1).Item(1)
txtPC.Text = Lib_9th_NLDataSet.tblContacts.Rows(1).Item(2)
txtMonintor.Text = Lib_9th_NLDataSet.tblContacts.Rows(1).Item(3)
txtKeyboard.Text = Lib_9th_NLDataSet.tblContacts.Rows(1).Item(4)
txtPhone.Text = Lib_9th_NLDataSet.tblContacts.Rows(1).Item(5)
txtlaptop.Text = Lib_9th_NLDataSet.tblContacts.Rows(1).Item(6)
End Sub
End Class
It seems like you might be getting mixed up between your DataSet and your TableAdapterManager.
First, we need to get the values from the text boxes.
empID = EmployeeIDTxt.Text
dob = DateOfBirthTxt.Text
mailStation = MailStationTxt.Text
eFirst = FNameTxt.Text
prefName = PrefNameTxt.Text
eLast = LNameTxt.Text
homeAddress = Address1Txt.Text
city = CityTxt.Text
state = StateTxt.Text
zip = ZipTxt.Text
payGroup = PayGroupTxt.Text
fileNo = FileNoTxt.Text
begDT = BegDtTxt.Text
Now, we can reference the fields in our Update query as variables, and add parameters to them so we can prevent SQL Injection.
'This is your update statement
Dim updateQry As String = String.Empty
updateQry = "UPDATE YOURTABLE"
updateQry &= " SET EMPL_ID = #EmployeeID,EMPL_LAST_NM = #LastName, EMPL_FIRST_NM = #FirstName, EMPL_PREFRD_NM = #PrefName,"
updateQry &= " EMPL_BIRTH_DT = #DateOfBirth, EMPL_MAIL_STN_CD = #MS, EMPL_ADDR1_TXT = #HomeAddress,"
updateQry &= " EMPL_ADDR2_TXT = #Add2, EMPL_CITY_NM = #City, EMPL_STATE_CD = #State, EMPL_POSTL_CD = #Zip,"
updateQry &= " WHERE EMPL_ID = #EmployeeID ;"
'Declare Connection String
Using sqlConnection As New OleDBConnection(myConn)
Using cmd As New OleDBCommand()
'Declare variable for SQL command
With cmd
.Connection = sqlConnection
.CommandType = CommandType.Text
.CommandText = updateQry
'Prevent against SQL Injection -> Add Parameters
With .Parameters
.AddWithValue("#EmployeeID", empID)
.AddWithValue("#FirstName", eFirst)
.AddWithValue("#LastName", eLast)
.AddWithValue("#PrefName", prefName)
.AddWithValue("#DateOfBirth", dob)
.AddWithValue("#MS", mailStation)
.AddWithValue("#HomeAddress", homeAddress)
.AddWithValue("#City", city)
.AddWithValue("#State", state)
.AddWithValue("#Zip", zip)
End With
End With
Try
sqlConnection.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Error Updating " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Using
End Using
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
MsgBox("" & FNameTxt.Text & " " & LNameTxt.Text & " has been updated")
End Try
Now, we need to change a few things.
Replace myConn with your connection string and open it in this instance (in the btnUpdate sub)
Change all of the fields in the Parameter list to your variables. ("EmployeeID" is the parameter I am providing for the variable empID)
Your WHERE clause is going to depend on what records you want to update. That's for you to decide. Is there a primary key you can reference like I do with EmployeeID?
Replace EMPL_ fields with your field names.
For clarification, the "#EmployeeID" parameter is the safe way of writing to the database of adding empID directly.
There are a couple other ways to do this, such as OleDbUpdateCommand, etc.
Hope this helps you.

A NullReferenceException is thrown [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
Using vb.NET I am trying to pull data from a database via a dataset but when running the code for the button, I get this error:
"An unhandled exception of type 'System.NullReferenceException' occurred in Full Program.exe
Additional information: Object reference not set to an instance of an object."
Here is my code, what is wrong with it?
Public Class mod_data
Dim inc As Integer
Dim con As OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim ds As DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Dim MaxRows As Integer
Private Sub mod_data_Load(sender As Object, e As EventArgs) Handles MyBase.Load
dbProvider = "PROVIDER=Microsoft.ACE.12.0;"
dbSource = "\\fin01\JBU Visual Basic ICT\Ben\Full Program\Full Program\Component_Database.accdb;"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "SELECT * FROM tblComponent_List"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "Component_List")
con.Close()
MaxRows = ds.Tables("Component_List").Rows.Count
inc = -1
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
txtComponent_ID.Text = ds.Tables("Component_List").Rows(1).Item(0)
txtComponent_Name.Text = ds.Tables("Component_List").Rows(1).Item(1)
'(...)
End Sub
'(...)
End Sub
#Crono
It is still throwing up the same error. This is the new code:
Still not working. This is the new code:
Public Class mod_data
Dim inc As Integer
Dim con As OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim ds As DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Dim MaxRows As Integer
Private Sub mod_data_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ds = New DataSet("Component_DatabaseDataSet3")
con = New OleDb.OleDbConnection("\\fin01\JBU Visual Basic ICT\Ben\Full Program\Full Program\Component_Database.accdb")
dbProvider = "PROVIDER=Microsoft.ACE.12.0;"
dbSource = "\\fin01\JBU Visual Basic ICT\Ben\Full Program\Full Program\Component_Database.accdb;"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "SELECT * FROM tblComponent_List"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "Component_List")
con.Close()
MaxRows = ds.Tables("Component_List").Rows.Count
inc = -1
End Sub
Private Sub NavigateRecords()
txtComponent_ID.Text = ds.Tables("Component_List").Rows(inc).Item(0)
txtComponent_Name.Text = ds.Tables("Component_List").Rows(inc).Item(1)
End Sub
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
If inc <> MaxRows - 1 Then
inc = inc + 1
NavigateRecords()
Else
MsgBox("No More Rows")
End If
End Sub
Private Sub btnPrevious_Click(sender As Object, e As EventArgs) Handles btnPrevious.Click
If inc > 0 Then
inc = inc - 1
NavigateRecords()
ElseIf inc = -1 Then
MsgBox("No Records Yet")
ElseIf inc = 0 Then
MsgBox("First Record")
End If
End Sub
Private Sub btnLast_Click(sender As Object, e As EventArgs) Handles btnLast.Click
If inc <> MaxRows - 1 Then
inc = MaxRows - 1
NavigateRecords()
End If
End Sub
Private Sub btnFirst_Click(sender As Object, e As EventArgs) Handles btnFirst.Click
If inc <> 0 Then
inc = 0
NavigateRecords()
End If
End Sub
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
ds.Tables("Component_List").Rows(inc).Item(0) = txtComponent_ID.Text
ds.Tables("Component_List").Rows(inc).Item(1) = txtComponent_Name.Text
MsgBox("Data updated")
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Tables("Component_List").Rows(inc).Delete()
MaxRows = MaxRows - 1
inc = 0
da.Update(ds, "Component_List")
NavigateRecords()
If MessageBox.Show("Do you really want to Delete this Record?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = DialogResult.No Then
MsgBox("Operation Cancelled")
Exit Sub
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
txtComponent_ID.Text = ds.Tables("Component_List").Rows(1).Item(0)
txtComponent_Name.Text = ds.Tables("Component_List").Rows(1).Item(1)
End Sub
End Class
Your con connection object has not been instantiated. Put this line in before trying to set the connection string:
con = New OleDb.OleDbConnection()
You are going to have the same problem for ds. It should be instantiated before calling the adapter's Fill method.
ds = New DataSet()
As an additional advice, I'd suggest you remove the second parameter passed to the adapter's Fill method and fetch the DataTable instance this way:
MaxRows = ds.Tables(0).Rows.Count
And finally, next time, use the debugger to solve this kind of problem. It will be much easier and faster than asking on SO. ;)
You do not seem to have initialised 'con', thus it will contain null.
Initialise it before using it.
con = New OleDbConnection()

unknown syntax error at the end of data adapter/set code vbasic

Public Class Form4
Dim sql As String 'Declaring sql as a string
Dim con As New OleDb.OleDbConnection 'Declaring con as a new connection
Dim da As OleDb.OleDbDataAdapter 'Declaring da as a data adapter
Dim ds As New DataSet 'Declaring ds as a new data set
Dim Inc As Integer 'Declaring inc As an integer
Dim Maxrows As Integer 'Declaring maxrows as an integer
'inside of the connection, i have to fill the dataset, and then fill the adapter with the dataset
Private Sub Form4_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
con.ConnectionString = "PROVIDER = Microsoft.Jet.OLEDB.4.0; Data Source = C:\Users\MadMaxHarl\Desktop\Thespellingbee\Resources\Spelling Bee1.mdb" 'States where the database is, as well as the provider
con.Open() 'Opens the connection
sql = "SELECT * FROM [WordsDefinitions] [WD]" 'The sql string is filled with the data from the table "Words + Definitions"
da = New OleDb.OleDbDataAdapter(sql, con) 'Makes da a new data adapter containing the connection and the sql string
da.Fill(ds, "WD")
con.Close() 'Closes the connection
Maxrows = ds.Tables("WD").Rows.Count
Inc = -1
End Sub
Private Sub navigaterecords()
txtword.Text = ds.Tables("WD").Rows(Inc).Item(1)
Txtdescription.Text = ds.Tables("WD").Rows(Inc).Item(2)
End Sub
Private Sub BtnBack_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnBack.Click
If inc > 0 Then
Inc = Inc - 1
navigaterecords()
Else
MsgBox("First Record")
End If
End Sub
Private Sub BtnNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnNext.Click
If Inc <> Maxrows - 1 Then
Inc = Inc + 1
navigaterecords()
Else
MsgBox("No More Rows")
End If
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
If Inc <> Maxrows - 1 Then
Inc = Maxrows - 1
navigaterecords()
End If
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
If Inc <> 0 Then
Inc = 0
navigaterecords()
End If
End Sub
Private Sub BtnExitSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnExitSave.Click
Dim cb As New OleDb.OleDbCommandBuilder(da) 'Command builder needed to change database, stored data adapter in the variable cb
ds.Tables("WD").Rows(Inc).Item(1) = txtword.Text
ds.Tables("WD").Rows(Inc).Item(2) = Txtdescription.Text
da.Update(ds, "WD")
MsgBox("It's working", MessageBoxButtons.OK)
End Sub
End Class
So at the end of this code, i get a massive syntax error that states "Syntax error (missing operator) in query expression '((Word Number = ?) AND ((? = 1 AND Word IS NULL) OR (Word = ?)) AND ((? = 1 AND Description IS NULL) OR (Description = ?)))'."
Anyone got any ideas?
EDIT: ok, this error is right at the end on da.update
2:the thing my sql is trying to connect to is a database that looks like:
Word Number Word Description
1 Hectare Unit Of Area
2 Active Being Busy
3 Amaze Surprise
4 Bound Leap And Jump
5 Cavern A Large Cave
6 Difficult Hard To Do
7 Frozen Turned To Ice
8 Garage Building For A Car
9 Jaguar Large Cat
10 Lemonade Fizzy Drink

My connection string is not quite right

Hi can someone help me with my connection string, I can navigate around my database but I can not add data to it. Thanks in advance my code is below, if someone an shred some light on it for me that would be great. So I can navigate but I can not add data or update data. I did have this working at one point but have since screed t up. If only I had done a backup of it :(
Imports System.Data.OleDb
Public Class adminPanel
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim ds As New DataSet
Dim sql As String
Dim da As New OleDb.OleDbDataAdapter
Dim inc As Integer
Dim MaxRows As Integer
Private Sub adminPanel(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim Builder As New OleDb.OleDbConnectionStringBuilder With
{
.ConnectionString = My.Settings.Database1
}
' Change it
Builder.DataSource = IO.Path.Combine(Application.StartupPath, "Database1.mdb")
lblName.Text = LoginForm.txtUserName.Text
If lblName.Text = LoginForm.txtUserName.Text Then
Builder.Add("Jet OLEDB:Database Password", "password")
Using con As New OleDb.OleDbConnection With {.ConnectionString = Builder.ConnectionString}
sql = "SELECT * FROM tblContacts"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "Database1")
'MsgBox("Database is now open")
MaxRows = ds.Tables("Database1").Rows.Count
inc = -1
End Using
End If
End Sub
Private Sub NavigateRecords()
UserName.Text = CStr(ds.Tables("Database1").Rows(inc).Item(1))
UserPassword.Text = CStr(ds.Tables("Database1").Rows(inc).Item(2))
UserTimer.Text = ds.Tables("Database1").Rows(inc).Item(3).ToString
End Sub
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
UserName.Text = CStr(ds.Tables("Database1").Rows(inc).Item(1))
UserPassword.Text = CStr(ds.Tables("Database1").Rows(inc).Item(2))
UserTimer.Text = CStr(ds.Tables("Database1").Rows(inc).Item(3))
da.Update(ds, "Database1")
MsgBox("Data updated")
End Sub
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
If inc <> MaxRows - 1 Then
inc = inc + 1
NavigateRecords()
Else
MsgBox("No More Rows")
End If
End Sub
Private Sub btnPrevious_Click(sender As Object, e As EventArgs) Handles btnPrevious.Click
If inc > 0 Then
inc = inc - 1
NavigateRecords()
Else
MsgBox("First Record")
End If
End Sub
Private Sub btnLast_Click(sender As Object, e As EventArgs) Handles btnLast.Click
If inc <> MaxRows - 1 Then
inc = MaxRows - 1
NavigateRecords()
End If
End Sub
Private Sub btnFirst_Click(sender As Object, e As EventArgs) Handles btnFirst.Click
If inc <> 0 Then
inc = 0
NavigateRecords()
End If
End Sub
Private Sub adminPanel_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
MsgBox("Data cleared")
btnCommit.Enabled = False
btnAddNew.Enabled = True
btnUpdate.Enabled = True
btnDelete.Enabled = True
inc = 0
NavigateRecords()
End Sub
Private Sub btnAddNew_Click(sender As Object, e As EventArgs) Handles btnAddNew.Click
btnCommit.Enabled = True
btnUpdate.Enabled = False
btnDelete.Enabled = False
btnAddNew.Enabled = False
UserName.Clear()
UserPassword.Clear()
UserTimer.Clear()
End Sub
Private Sub btnCommit_Click(sender As Object, e As EventArgs) Handles btnCommit.Click
If inc <> -1 Then
Dim con As New OleDb.OleDbCommandBuilder(da)
Dim dsNewRow As DataRow
dsNewRow = ds.Tables("Database1").NewRow()
dsNewRow.Item("UserName") = UserName.Text
dsNewRow.Item("UserPassword") = UserPassword.Text
dsNewRow.Item("UserTimer") = UserTimer.Text
ds.Tables("Database1").Rows.Add(dsNewRow)
da.Update(ds, "Database1")
MsgBox("New Record added to the Database")
btnCommit.Enabled = False
btnAddNew.Enabled = True
btnUpdate.Enabled = True >
btnDelete.Enabled = True
End If
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
If MessageBox.Show("Do you really want to Delete this Record?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = DialogResult.No Then
MsgBox("Operation Cancelled")
Exit Sub
End If
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Tables("Database1").Rows(inc).Delete()
MaxRows = MaxRows - 1
inc = 0
da.Update(ds, "Database1")
NavigateRecords()
End Sub
End Class
It has nothing to do with your connection string. The code in btnUpdate_Click is not updating the database, it is updating the textboxes.
edit
btnUpdate_Click should read something like (untested code)
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
ds.Tables("Database1").Rows(inc).Item("UserName") = UserName.Text
ds.Tables("Database1").Rows(inc).Item("Password") = UserPassword.Text
ds.Tables("Database1").Rows(inc).Item("UserTimer") = UserTimer.Text
da.Update(ds, "Database1")
MsgBox("Data updated")
End Sub

VB: How to bind a DataTable to a DataGridView?

I know this is a basic question that has already been answered thousand times, but I can't make it work.
I am working in Visual Studio 2010 and have two forms in my Windows Application. In the first one (Main.vb), the user enters his inputs and the calculation takes place. In the second one (DataAnalysis.vb) the calculation results are displayed.
In Main.vb, I create the temp table that will contains all the intermediary calculation steps:
Dim tableTempJDL As DataTable = New DataTable("TempJDL")
Dim column As DataColumn
column = New DataColumn("ID", GetType(System.Int32))
tableTempJDL.Columns.Add(column)
column = New DataColumn("PthObjekt", GetType(System.Double))
tableTempJDL.Columns.Add(column)
'further columns are after created using the same method
Then, in DataAnalysis.vb, I try to display the DataTable tableTempJDL into the DataGridViewBerechnung:
Public bindingSourceBerechnung As New BindingSource()
Me.DataGridViewBerechnung.DataSource = Me.bindingSourceBerechnung
But then I don't understand how to fill the DataGridView...
Simply, you can make your table as the datasource of bindingsource in following way:
Me.bindingSourceBerechnung .DataSource = tableTempJDL
Later on, you can bind above binding source in your datagridview in following way:
Me.DataGridViewBerechnung.DataSource = Me.bindingSourceBerechnung
Public Class Form1
Dim CON As New SqlConnection
Dim CMD As New SqlCommand
Dim dt As New DataTable
Public Sub DbConnect()
If CON.State = ConnectionState.Open Then DbClose()
CON.ConnectionString = "Data Source = yourservername;Initial Catalog=your database name;Integrated Security=True"
CON.Open()
End Sub
Public Sub DbClose()
CON.Close()
CON.Dispose()
End Sub
Public Sub enabletext()
TextBox1.Enabled = True
End Sub
Public Sub CLEARFEILDS()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
ComboBox1.DataSource = Nothing
ComboBox1.SelectedIndex = 0
DataGridView2.Rows.Clear()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ComboBox1.Select()
TextBox4.Enabled = False
DataGridView1.Visible = False
TextBox5.Visible = False
'AUTOSEACH()
DbConnect()
Dim SELECTQUERY As String = "SELECT PROD_CODE FROM TBLPRODUCT"
Dim MYCOMMAND As New SqlCommand(SELECTQUERY, CON)
Dim MYREADER As SqlClient.SqlDataReader
MYREADER = MYCOMMAND.ExecuteReader
Prod_Code.Items.Clear()
While MYREADER.Read
Prod_Code.Items.Add(MYREADER("PROD_CODE"))
End While
DbClose()
End Sub
Public Function InvCodeGen(ByVal CurrCode As String) As String
Dim RightSix As String = Microsoft.VisualBasic.Right(Trim(CurrCode), 3)
Dim AddValue As Integer = Microsoft.VisualBasic.Val(RightSix) + 1
Dim RetValue As String
If Microsoft.VisualBasic.Len(AddValue.ToString) = 1 Then
RetValue = "00" + AddValue.ToString
ElseIf (Microsoft.VisualBasic.Len(AddValue.ToString) = 2) Then
RetValue = "000" + AddValue.ToString
Else
RetValue = AddValue.ToString
End If
Return RetValue
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
CreateNewCode()
TextBox1.Enabled = False
DataGridView1.Visible = False
TextBox5.Visible = False
ComboBox1.Visible = True
AddCustomer()
'GridView2Load(GetDataGridView2())
End Sub
Private Sub CreateNewCode()
Dim CurrCode As String = ""
'Dim NewCode As String = "INV"
Dim NewCode As Integer
Dim mySelectQuery As String = "SELECT MAX(INV_NO) AS INVNO FROM TBLINV_HEADER"
Dim myCommand As New SqlClient.SqlCommand(mySelectQuery, CON)
myCommand.CommandType = CommandType.Text
Dim myReader As SqlClient.SqlDataReader
DbConnect()
myReader = myCommand.ExecuteReader()
Do While myReader.Read()
If IsDBNull(myReader("INVNO")) Then
myReader.Close()
Dim myNewYearQuery As String = "SELECT MAX(INV_NO) AS INVNO FROM TBLINV_HEADER"
Dim myNewYearCommand As New SqlClient.SqlCommand(myNewYearQuery, CON)
myNewYearCommand.CommandType = CommandType.Text
Dim myNewYearReader As SqlClient.SqlDataReader
myNewYearReader = myNewYearCommand.ExecuteReader()
Do While myNewYearReader.Read()
CurrCode = Trim(myNewYearReader("INVNO").ToString)
Loop
myNewYearReader.Close()
Exit Do
Else
CurrCode = Trim(myReader("INVNO").ToString)
myReader.Close()
Exit Do
End If
Loop
DbClose()
NewCode = Trim(InvCodeGen(CurrCode))
TextBox1.Text = CInt(NewCode)
End Sub
Private Sub AddCustomer()
Dim dsCusCode As New DataSet
dsCusCode.Reset()
ComboBox1.Items.Clear()
Dim myCusCodeQuery As String = "SELECT CUST_CODE as Custcode FROM TBLCUSTOMER"
Dim daCusCode As New SqlClient.SqlDataAdapter(myCusCodeQuery, CON)
DbConnect()
daCusCode.Fill(dsCusCode, "TBLCUSTOMER")
DbClose()
Dim x As Integer
For x = 0 To dsCusCode.Tables(0).Rows.Count - 1
ComboBox1.Items.Add(dsCusCode.Tables(0).Rows(x).Item("Custcode").ToString)
'TextBox3.Text = dsCusCode.Tables(0).Rows(x).Item("custname").ToString
Next
ComboBox1.SelectedIndex = -1
x = Nothing
myCusCodeQuery = Nothing
dsCusCode.Dispose()
daCusCode.Dispose()
dsCusCode = Nothing
dsCusCode = Nothing
End Sub
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim Code As String
Code = ComboBox1.Text
Dim dsCode As New DataSet
dsCode.Reset()
Dim myCodeQuery As String = "SELECT cust_name as custname, cust_add1 as custadd FROM TBLCUSTOMER where Cust_Code = '" & Code & "'"
Dim daCode As New SqlClient.SqlDataAdapter(myCodeQuery, CON)
DbConnect()
daCode.Fill(dsCode, "TBLCUSTOMER")
DbClose()
TextBox2.Text = dsCode.Tables(0).Rows(0).Item("custname").ToString
TextBox3.Text = dsCode.Tables(0).Rows(0).Item("custadd").ToString
myCodeQuery = Nothing
dsCode.Dispose()
daCode.Dispose()
dsCode = Nothing
dsCode = Nothing
End Sub
Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
For I As Integer = 0 To DataGridView2.Rows.Count - 1
Dim MYQUERY As String = "SELECT PROD_DESC , PROD_PRICE FROM TBLPRODUCT WHERE PROD_CODE='" & DataGridView2.Rows(I).Cells(1).Value & "'"
Dim MYCOMMAND As New SqlCommand(MYQUERY, CON)
DbConnect()
Dim MYREADER As SqlClient.SqlDataReader
MYREADER = MYCOMMAND.ExecuteReader
If MYREADER.Read() Then
DataGridView2.Rows(I).Cells(2).Value = MYREADER("PROD_DESC")
DataGridView2.Rows(I).Cells(3).Value = MYREADER("PROD_PRICE")
End If
DbClose()
Next
End Sub
Private Sub DataGridView2_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView2.CellFormatting
DataGridView2.Rows(e.RowIndex).Cells(0).Value = CInt(e.RowIndex + 1)
End Sub
Private Sub DataGridView2_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView2.CellEndEdit
For I As Integer = 0 To DataGridView2.Rows.Count - 1
Dim QTY As Double = DataGridView2.Rows(I).Cells(4).Value
Dim PRICE As Double = DataGridView2.Rows(I).Cells(3).Value
Dim AMOUNT As Double = QTY * PRICE
DataGridView2.Rows(I).Cells(5).Value = AMOUNT
Next
' SUM OF AMOUNT TOTAL
Dim COLSUM As Decimal = 0
For Each ROW As DataGridViewRow In DataGridView2.Rows
If Not IsDBNull(ROW.Cells(5).Value) Then
COLSUM += ROW.Cells(5).Value
End If
Next
TextBox4.Text = COLSUM
End Sub
'SAVE
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
If MsgBox("Are you sure want to save this record?", vbYesNo + vbQuestion) = vbYes Then
updateinvheader()
updategridvalue()
CLEARFEILDS()
End If
End Sub
Private Sub updateinvheader()
Dim insertquery1 As String = "insert into TBLINV_HEADER(inv_no,inv_date,inv_cust) values(#inv_no,#inv_date,#inv_cust)"
Dim command As New SqlCommand(insertquery1, CON)
command.Parameters.AddWithValue("#inv_no", TextBox1.Text)
command.Parameters.AddWithValue("#inv_date", DateTime.Now)
command.Parameters.AddWithValue("#inv_cust", ComboBox1.Text)
DbConnect()
command.ExecuteNonQuery()
DbClose()
End Sub
Private Sub updategridvalue()
Dim i As Integer
Dim insertquery2 As String = "insert into TBLINV_detail(inv_lno,inv_no,inv_prod,inv_qty,inv_Price) values(#inv_lno,#inv_no,#inv_prod,#inv_qty,#inv_Price)"
Dim command As New SqlCommand(insertquery2, CON)
For i = 0 To DataGridView2.RowCount - 1
If DataGridView2.Rows(i).Cells(1).Value = "" Then
GoTo 100
Else
command.Parameters.AddWithValue("#inv_lno", DataGridView2.Rows(i).Cells(0).RowIndex + 1)
'command.Parameters.AddWithValue("#inv_lno", DataGridView2.Rows(i).Cells(0).)
command.Parameters.AddWithValue("#inv_no", TextBox1.Text)
command.Parameters.AddWithValue("#inv_prod", DataGridView2.Rows(i).Cells(1).Value)
command.Parameters.AddWithValue("#inv_qty", DataGridView2.Rows(i).Cells(4).Value)
command.Parameters.AddWithValue("#inv_Price", DataGridView2.Rows(i).Cells(3).Value)
End If
DbConnect()
command.ExecuteNonQuery()
DbClose()
100: command.Parameters.Clear()
Next
MsgBox("data saved successfuly")
End Sub
Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click
DataGridView1.Visible = True
TextBox5.Visible = True
ComboBox1.Visible = False
DbConnect()
Dim MYQUERY As String = "Select * FROM TBLCUSTOMER" &
" INNER Join TBLINV_HEADER ON TBLINV_HEADER.INV_CUST = TBLCUSTOMER.CUST_CODE" &
" WHERE TBLINV_HEADER.INV_NO ='" & TextBox1.Text & "'"
Dim CMD As New SqlCommand(MYQUERY, CON)
Dim DA As New SqlDataAdapter
DA.SelectCommand = CMD
Dim DT As New DataTable
DA.Fill(DT)
If DT.Rows.Count > 0 Then
MsgBox(DT.Rows(0)(1).ToString())
'ComboBox1.Text = DT.Rows(0)(1).ToString()
ComboBox1.Visible = False
TextBox5.Text = DT.Rows(0)(1).ToString()
TextBox2.Text = DT.Rows(0)(2).ToString()
TextBox3.Text = DT.Rows(0)(3).ToString()
End If
DbClose()
DataGridView1.DataSource = GETPRODUCTDETAILS()
End Sub
Private Function GETPRODUCTDETAILS() As DataTable
Dim PRODUCTDET As New DataTable
DbConnect()
Dim MYQUERY As String = " SELECT TBLINV_DETAIL.INV_LNO, TBLINV_DETAIL.INV_PROD, TBLPRODUCT.PROD_DESC, TBLINV_DETAIL.INV_PRICE, TBLINV_DETAIL.INV_QTY, (TBLINV_DETAIL.INV_QTY*TBLINV_DETAIL.INV_PRICE) AS AMOUNT FROM TBLINV_DETAIL " &
" INNER JOIN TBLPRODUCT On TBLPRODUCT.PROD_CODE = TBLINV_DETAIL.INV_PROD " &
" WHERE TBLINV_DETAIL.INV_NO='" & TextBox1.Text & "'"
Dim CMD As New SqlCommand(MYQUERY, CON)
Dim READER As SqlDataReader = CMD.ExecuteReader()
PRODUCTDET.Load(READER)
DbClose()
Return PRODUCTDET
End Function
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim DELETEQUERY As String = "DELETE FROM TBLINV_DETAIL WHERE TBLINV_DETAIL.INV_NO= '" & TextBox1.Text & "'"
Dim DELETEQUERY2 As String = "DELETE FROM TBLINV_HEADER WHERE TBLINV_HEADER.INV_NO= '" & TextBox1.Text & "'"
Dim CMD As New SqlCommand(DELETEQUERY, CON)
Dim CMD2 As New SqlCommand(DELETEQUERY2, CON)
DbConnect()
CMD.ExecuteNonQuery()
CMD2.ExecuteNonQuery()
DbClose()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
ComboBox1.DataSource = Nothing
DataGridView1.DataSource = Nothing
MsgBox("DATA DELETED SUCCESSFULLY")
End Sub
End Class