Index Out Of Range Exception In VB.NET - vb.net

When I run the following code, after the ColourAddition(selectedstyle,styleselection.getIndex)="Y" line, I get an error every time and when I run the code without the aforementioned line, the program is a success. Please help me figure it out
Public Class Form1
Dim dbcon As New OleDb.OleDbConnection
Dim DR As OleDb.OleDbDataReader
Dim dr1 As OleDb.OleDbDataReader
Dim com As New OleDb.OleDbCommand
Dim com1 As New OleDb.OleDbCommand
Dim ChkdItm As Integer
Dim NoOfStyles As Integer
Dim NoOfColours As Integer
Dim SelectedStyle As Integer
Dim temp As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
dbcon.ConnectionString = "Provider= Microsoft.Ace.OLEDB.12.0; Data Source= CheckedListBox.accdb"
dbcon.Open()
com.CommandText = "Select * from ColourTable"
com1.CommandText = "Select * from StyleTable"
com1.Connection = dbcon
com.Connection = dbcon
DR = com.ExecuteReader
dr1 = com1.ExecuteReader
While dr1.Read
NoOfStyles += 1
End While
While DR.Read
ColoursClb.Items.Add(DR.GetString(1))
NoOfColours += 1
End While
SelectedStyle = StyleSelection.getIndex
End Sub
Public colourAddition(NoOfStyles, NoOfColours) As String
Private Sub AddColourBtn_Click(sender As Object, e As EventArgs) Handles AddColourBtn.Click
If ColoursClb.CheckedItems.Count > 0 Then
For Each ChkdItm In ColoursClb.CheckedIndices
colourAddition(SelectedStyle, StyleSelection.getIndex) = "Y"
Next
End If
End Sub
Private Sub Form1_Closed(sender As Object, e As EventArgs) Handles Me.Closed
StyleSelection.Show()
End Sub
End Class
The error is showing on the line where "Next" is written

Related

Get Image from SQL using Listbox to picturebox VB

i'm trying to get the image from SQL to picturebox using Listbox in in VB.
here is my sql sample table.
and here is my VB Design form, so what I'm trying to do is when I load the form, if an item in the listbox is selected, i want it to get the image(Binary Data) from sql to picturebox in vb net.
and the code I'm working with it give me this error:
VB full code:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
connect()
Dim co As New SqlConnection("Data Source=WXCQSDQSD\SQLEXPRESS;Initial Catalog=food;Integrated Security = True")
co.Open()
Dim com As New SqlCommand("SELECT Image from Items where ItemName = '" & ListBox1.SelectedIndex & "'", co)
Dim img As Byte() = DirectCast(com.ExecuteScalar(), Byte())
Dim ms As MemoryStream = New MemoryStream(img)
Dim dt = GetDataFromSql()
Dim BndSrc As New BindingSource()
BndSrc.DataSource = dt
ListBox1.DisplayMember = "ItemName"
ListBox1.DataSource = BndSrc
TextBox1.DataBindings.Add("Text", BndSrc, "ItemID")
TextBox2.DataBindings.Add("Text", BndSrc, "ItemName")
TextBox3.DataBindings.Add("Text", BndSrc, "Details")
PictureBox1.Image = Image.FromStream(ms)
End Sub
Private Function GetDataFromSql() As DataTable
Dim dt As New DataTable
Using connection As New SqlConnection("Data Source=WXCQSDQSD\SQLEXPRESS;Initial Catalog=food;Integrated Security = True"),
cmd As New SqlCommand("select * FROM Items", connection)
connection.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
Remove the picture retrieval from the Form.Load. We have selected all the data in the GetDataFromSql function. The magic happens in the ListBox1.SelectedIndexChanged method.
The SelectedIndexChanged will occur as a result of the code in the Form.Load and every time the selection changes. When we bind the the list box to to binding source the entire row is added as a DataRowView. We can use this to get the data in the Image column. First check if the field is null. Next cast to a byte array. Take the byte array and pass it to the constructor of a MemoryStream. Streams need to be disposed so it is in a Using block. Finally the stream can be assigned to the Image property of the PictureBox.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt = GetDataFromSql()
Dim BndSrc As New BindingSource()
BndSrc.DataSource = dt
ListBox1.DisplayMember = "ItemName"
ListBox1.DataSource = BndSrc
TextBox1.DataBindings.Add("Text", BndSrc, "ItemID")
TextBox2.DataBindings.Add("Text", BndSrc, "ItemName")
TextBox3.DataBindings.Add("Text", BndSrc, "Details")
End Sub
Private Function GetDataFromSql() As DataTable
Dim dt As New DataTable
Using connection As New SqlConnection("Data Source=WXCQSDQSD\SQLEXPRESS;Initial Catalog=food;Integrated Security = True"),
cmd As New SqlCommand("select * FROM Items", connection)
connection.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
Dim row = DirectCast(ListBox1.SelectedItem, DataRowView)
If row("Image") IsNot Nothing Then
Dim b() As Byte = DirectCast(row("Image"), Byte()) '< ------ Cast the field to a Byte array.
Using ms As New System.IO.MemoryStream(b)
PictureBox1.Image = System.Drawing.Image.FromStream(ms)
End Using
Else
PictureBox1.Image = Nothing
End If
End Sub
EDIT
I switched the code over to a database I have available for testing. Even though it is not your database, I am sure you will be able to follow the code.
Here is the schema of my database.
The main difference is I moved the DataTable to a class level variable so it can be seen from all methods. I changed the GetDataFromSql to a Sub. It adds the data to the class level DataTable (Bounddt). The AddItem method first gets the Byte() from a file. The row is added to the DataTable with an Object array with elements that match the DataTable.
Private Bounddt As New DataTable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
GetDataFromSql()
Dim BndSrc As New BindingSource()
BndSrc.DataSource = Bounddt
ListBox1.DisplayMember = "CustomerID"
ListBox1.DataSource = BndSrc
TextBox1.DataBindings.Add("Text", BndSrc, "CustomerID")
TextBox2.DataBindings.Add("Text", BndSrc, "CustomerName")
End Sub
Private Sub GetDataFromSql()
Using connection As New SqlConnection("Data Source=****;Initial Catalog='Small Database';Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"),
cmd As New SqlCommand("select * FROM Sales.Customer", connection)
connection.Open()
Using reader = cmd.ExecuteReader
Bounddt.Load(reader)
End Using
End Using
'Return dt
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
Dim row = DirectCast(ListBox1.SelectedItem, DataRowView)
If row("Picture") IsNot Nothing Then
Dim b() As Byte = DirectCast(row("Picture"), Byte()) '< ------ Cast the field to a Byte array.
Using ms As New System.IO.MemoryStream(b)
PictureBox1.Image = System.Drawing.Image.FromStream(ms)
End Using
Else
PictureBox1.Image = Nothing
End If
End Sub
Private Sub AddItem()
Dim picture = GetByteArr("C:\Users\maryo\OneDrive\Documents\Graphics\Animals\squirrel.png")
Bounddt.Rows.Add({5, "George", 74, 62, "George", picture})
End Sub
Private Function GetByteArr(path As String) As Byte()
Dim img = Image.FromFile(path)
Dim arr As Byte()
Dim imgFor As Imaging.ImageFormat
Dim extension = path.Substring(path.LastIndexOf(".") + 1)
'There is a longer list of formats available in ImageFormat
Select Case extension
Case "png"
imgFor = Imaging.ImageFormat.Png
Case "jpg", "jpeg"
imgFor = Imaging.ImageFormat.Jpeg
Case "bmp"
imgFor = Imaging.ImageFormat.Bmp
Case Else
MessageBox.Show("Not a valid image format")
Return Nothing
End Select
Using ms As New MemoryStream
img.Save(ms, imgFor)
arr = ms.ToArray
End Using
Return arr
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
AddItem()
End Sub
Imports System.Data.SqlClient
Imports System.IO
Public Class Form1
Dim con As SqlConnection
Dim cmd As SqlCommand
Dim rdr As SqlDataReader
Dim da As SqlDataAdapter
Private Const cs As String = "ConnectionString"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
con = New SqlConnection(cs)
con.Open()
cmd = New SqlCommand("select * from [dbo].[Item_Details]", con)
rdr = cmd.ExecuteReader()
While rdr.Read
ListBox1.Items.Add(rdr(1))
End While
con.Close()
End Sub
Private Sub ListBox1_MouseClick(sender As Object, e As MouseEventArgs) Handles ListBox1.MouseClick
Try
con = New SqlConnection(cs)
con.Open()
da = New SqlDataAdapter("Select * from Item_Details where itemname='" & ListBox1.SelectedItem.ToString() & "'", con)
Dim dt As New DataTable
da.Fill(dt)
For Each row As DataRow In dt.Rows
TextBox1.Text = row(0).ToString()
TextBox2.Text = row(1).ToString()
TextBox3.Text = row(2).ToString()
Dim data As Byte() = row(3)
Dim ms As New MemoryStream(data)
PictureBox1.Image = Image.FromStream(ms)
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class

VB.Net, Problem updating table from DataGridView

This is my first post so forgive me if I goof!
I am trying to update myself from VBA to VB.Net. Using loads of help from Google etc I am doing Ok except when I try to update my table from a DataGridView. It just does not update. What I would like is that a cell is update on change. My code so far is shown (I have tried all sorts of builder, tables etc so my code may have a smattering of these that are redundant):
Imports System.Data.SqlClient
Imports System.IO
Imports Microsoft.SqlServer
Public Class FrmData
Private dsS As DataSet = New DataSet
Private adpS As SqlDataAdapter
Private builder As SqlCommandBuilder
Private bsource = New BindingSource
Private Sub FrmData_Load(sender As Object, e As EventArgs) Handles
MyBase.Load
Dim sqlS = "SELECT [Data].[Date] AS [Date] ,
[Data].[PaidBy] AS [Paid By] ,
[Data].[PaidAmount] AS [Paid Amount (£)],
[Data].[AmountLeft] AS [Amount Left (£)]
FROM [Data] WHERE [Data].[Name]= '" & strName & "'
ORDER BY [Data].[Date] DESC"
Dim adpS As SqlDataAdapter
adpS = New SqlDataAdapter(sqlS, connection)
builder = New SqlCommandBuilder(adpS)
Dim dTable As New DataTable
bsource.DataSource = dTable
bsource.EndEdit()
adpS.Fill(dTable)
connection.Close()
DataGridView1.DataSource = dTable
End Sub
Private Sub DataGridView1_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
DataGridView1.EndEdit()
Dim dt As DataTable
dt = TryCast(DataGridView1.DataSource, DataTable)
Dim x As Integer = 0
If dt.GetChanges() Is Nothing Then
MessageBox.Show("The table contains no changes to save.")
Else
Dim builder = New SqlCommandBuilder(adpS)
Dim rowsAffected As Integer = adpS.Update(dt)
If rowsAffected = 0 Then
MessageBox.Show("No rows were affected by the save operation.")
Else
MessageBox.Show(rowsAffected & " rows were affected by the save operation.")
End If
End If
End Sub
End Class
Any help would be appreciated.
This is for SQL Server, right. Try it like this.
Imports System.Data.SqlClient
Public Class Form1
Dim sCommand As SqlCommand
Dim sAdapter As SqlDataAdapter
Dim sBuilder As SqlCommandBuilder
Dim sDs As DataSet
Dim sTable As DataTable
Private Sub load_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles load_btn.Click
Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True"
Dim sql As String = "SELECT * FROM Stores"
Dim connection As New SqlConnection(connectionString)
connection.Open()
sCommand = New SqlCommand(sql, connection)
sAdapter = New SqlDataAdapter(sCommand)
sBuilder = New SqlCommandBuilder(sAdapter)
sDs = New DataSet()
sAdapter.Fill(sDs, "Stores")
sTable = sDs.Tables("Stores")
connection.Close()
DataGridView1.DataSource = sDs.Tables("Stores")
DataGridView1.ReadOnly = True
save_btn.Enabled = False
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
End Sub
Private Sub new_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles new_btn.Click
DataGridView1.[ReadOnly] = False
save_btn.Enabled = True
new_btn.Enabled = False
delete_btn.Enabled = False
End Sub
Private Sub delete_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles delete_btn.Click
If MessageBox.Show("Do you want to delete this row ?", "Delete", MessageBoxButtons.YesNo) = DialogResult.Yes Then
DataGridView1.Rows.RemoveAt(DataGridView1.SelectedRows(0).Index)
sAdapter.Update(sTable)
End If
End Sub
Private Sub save_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save_btn.Click
sAdapter.Update(sTable)
DataGridView1.[ReadOnly] = True
save_btn.Enabled = False
new_btn.Enabled = True
delete_btn.Enabled = True
End Sub
End Class
After two days working on this, I finally got it right for myself! Also, I had an eye on #ryguy72 codes as well. these are the steps you can take to get there:
Step 1: Drag and drop DataGridView into your form
Step 2: In the App.config add this between configuration:
<connectionStrings>
<add name="ehsanConnection" connectionString="Data Source=XXX
; User= XX; Password= XXX" ProviderName="System.Data.SqlClient"/>
</connectionStrings>
Step 3: The code below shows how you can get the DataGridView programmatically right, it worked perfectly fine for me.
Dim sCommand As SqlCommand
Dim sAdapter As SqlDataAdapter
Dim sBuilder As SqlCommandBuilder
Dim sDs As DataSet
Dim sTable As DataTable
Dim connStr As String =
ConfigurationManager.ConnectionStrings("ehsanConnection").ToString
Dim connStri = New SqlConnection(connStr)
Dim sql As String = "SELECT * FROM [Ehsan].[dbo].[Data]"
sCommand = New SqlCommand(sql, connStri)
sAdapter = New SqlDataAdapter(sCommand)
sBuilder = New SqlCommandBuilder(sAdapter)
sDs = New DataSet()
sAdapter.Fill(sDs, "Data")
sTable = sDs.Tables("Data")
connStri.Close()
DataGridView1.DataSource = sDs.Tables("Data")
The main point here was that I had to use [Ehsan].[dbo].[Data] not only the name of the table, "Data". Actually, it didn't work for me that way and it kept complaining!
Step 4: If you want to update your database after you changed some of the records in datagridview, use this code :
sAdapter.Update(sDs.Tables(0))
Main important point is that: "you have to set a primary key in your table first otherwise it won't work!"

How do I multiply the value in the textbox and the column in listview?

See picI'm not familiar with vb.net. So, what I'm trying to do is when I click the chosen product and I put the qty. The Total price will show the multiplied value of the qty and price in the listview. I put the code in case 2 since it is the price but when I run it, it displays 0 then when I change it with a value of 2, it doesn't multiply. Here's my code so far:
Imports System.Data.SqlClient
Imports System.IO
Public Class Form2
Dim con As SqlConnection = New SqlConnection("server=.\SQL;database=try;Trusted_Connection=TRUE")
Dim cmd As SqlCommand
Dim cmd2 As SqlCommand
Dim rdr As SqlDataReader
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
con.Open()
con.Close()
list()
End Sub
Sub list()
con.Open()
cmd = New SqlCommand("SELECT * FROM ProductTable", con)
rdr = cmd.ExecuteReader
ListView1.Items.Clear()
If rdr.HasRows Then
Do While rdr.Read()
Dim arr As String() = New String(2) {}
Dim itm As ListViewItem
arr(0) = rdr("productID")
arr(1) = rdr("product")
arr(2) = rdr("price")
itm = New ListViewItem(arr)
ListView1.Items.Add(itm)
Loop
End If
con.Close()
End Sub
Private Sub ListView1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListView1.SelectedIndexChanged
With Me.ListView1
Dim i As Integer
For Each item As ListViewItem In ListView1.SelectedItems
i = item.Index
Next
Dim innercounter As Integer = 0
For Each subItem As ListViewItem.ListViewSubItem In ListView1.Items(i).SubItems
Dim myString As String = ListView1.Items(i).SubItems(innercounter).Text
Select Case innercounter
Case 2
txtqty.Text = 0.ToString()
txtqty.Text = CType(0, String)
txtqty.Text = CStr(0)
txtqty.Text = "0"
txtprice.Text = myString * txtqty.Text
End Select
innercounter += 1
Next
End With
End Sub
End Class
You can have a Function to multiply values in Textbox and ListView
Private Function calculate() As Integer
Dim price As Integer
Dim qty As Integer
Dim totalPrice As Integer
Try
price = CInt(ListView1.Items(ListView1.FocusedItem.Index).SubItems(2).Text)
qty = CInt(txtqty.Text)
totalPrice = price * qty
Catch ex As Exception
MsgBox("Invalid Inputs!")
End Try
Return totalPrice
End Function
Convert the Strings into Integers so that you can multiply it. CInt() is the code for converting texts to int. Surround it by Try Catch to handle invalid inputs.
Then call the Function in your ListView1.SelectedIndexChanged or txtqty_TextChanged
Private Sub txtqty_TextChanged(sender As Object, e As EventArgs) Handles txtqty.TextChanged
txtprice.Text = calculate().ToString
End Sub
Private Sub ListView1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListView1.SelectedIndexChanged
txtprice.Text = calculate().ToString
End Sub

Extract data from Query

Can you please teach me on how to extract data from SQL query access database and place it into a Variable holder? I've been struggling for a week already and i've been really trying hard, please advise Thanks
This is what i have done so far :
Imports System.Data.OleDb
Public Class ModifyForm
Dim connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source= c:\Databse\Company_db.accdb"
Dim conn As New OleDbConnection
Private Sub MainMenuButton_Click(sender As Object, e As EventArgs) Handles MainMenuButton.Click
Me.Close()
Form1.Show()
End Sub
Private Sub CloseButton_Click(sender As Object, e As EventArgs) Handles CloseButton.Click
Me.Close()
Form1.Close()
End Sub
Private Sub DeleteBut_Click(sender As Object, e As EventArgs) Handles DeleteBut.Click
End Sub
Private Sub ModifyForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the "Company_dbDataSet1.tbl_empinfo" table. You can move, or remove it, as needed.'
Me.Tbl_empinfoTableAdapter.Fill(Me.Company_dbDataSet1.tbl_empinfo)
End Sub
Private Sub eNumText_SelectedIndexChanged(sender As Object, e As EventArgs) Handles eNumText.SelectedIndexChanged
Dim empNum As String
Dim empFname As String
Dim empLname As String
Dim empDept As String
Dim empStat As String
Dim empYears As String
empNum = eNumText.Text
empFname = empFnameText.Text
empLname = empLnameText.Text
empDept = DeptText.Text
empStat = StatText.Text
empYears = yearstext.Text
MsgBox(empNum)
Dim conn As New OleDbConnection
conn.Open()
Dim SqlQuerry As String = "SELECT * FROM tbl_empinfo WHERE EmpID like empNum"
Dim SqlCommand As New OleDbCommand
Dim SqlAdapter As New OleDbDataAdapter
Dim Table As New DataTable
With SqlCommand
.CommandText = SqlQuerry
.Connection = conn
End With
With SqlAdapter
.SelectCommand = SqlCommand
.Fill(Table)
End With
DataGridView1.Rows.Clear()
For i = 0 To Table.Rows.Count - 1
With DataGridView1
.Rows.Add(Table.Rows(i)("EmpID"), (Table.Rows(i)("FirstName")))
End With
Next
'Dim dbSource = "Data Source= C:\Databse\Company_db.accdb"'
conn.Close()
End Sub
Forgetting about the extra code, as was mentioned already, all you need to do is declare your variables:
Dim DBID As Integer ' Or whatever type you're using for the ID field
Dim DBFirstName As String
Then inside the For/Next loop, just use:
DBID = Table.Rows(i)("EmpID")
DBFirstName = Table.Rows(i)("FirstName")
That is only if you're going to use the variables within the for/next loop, otherwise you'll be overwriting them for every record. If you need to store all the values, you'll have to use arrays instead.

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()