For loop producing IndexOutOfRange error - vb.net

I keep getting the following error and unsure has to how fix it. As a fairly new user to VB.NET, I think it is saying that there are no rows at that position? To compensate for this, I included an If statement to check the row count, but it is still producing this error. In fact, the messagebox is not firing at all. Can someone please advise as to how I can correct this error. Thanks
Link where code obtained: http://support.microsoft.com/kb/305271/en-us
There is no row at position 1.
Private Sub loadpages()
Dim i As Integer
Dim startRec As Integer
Dim endRec As Integer
Dim dtTemp As DataTable
'Dim dr As DataRow
'Duplicate or clone the source table to create the temporary table.
dtTemp = dtSource.Clone
If currentPage = PageCount Then
endRec = maxRec
Else
endRec = pageSize * currentPage
End If
startRec = recNo
'Copy the rows from the source table to fill the temporary table.
If dtSource.Rows.Count <> 0 Then
For i = startRec To endRec - 1
dtTemp.ImportRow(dtSource.Rows(i)) <--- ERROR HERE
recNo = recNo + 1
Next
Else
MessageBox.Show(dtSource.Rows.Count.ToString())
End If
frmMain.DGV.DataSource = dtTemp
DisplayPageInfo()
'fillPostings()
End Sub
combobox sub to change pagesize
Sub cmbpage()
'Set the start and max records.
pageSize = CInt(frmMain.cmbPageSize.Text)
maxRec = dtSource.Rows.Count
PageCount = maxRec \ pageSize
MessageBox.Show(CStr(maxRec))
' Adjust the page number if the last page contains a partial page.
If (maxRec Mod pageSize) > 0 Then
PageCount = PageCount + 1
End If
'Initial seeings
currentPage = 1
recNo = 0
' Display the content of the current page.
UDGfillPostings()
loadpages()
End Sub

you have assigned startRec to 1,so it is throwing error when dtSource.Rows(1),as there is only one element in the array
you can rectify this by using dtSource.Rows(i-1)

You probably want this looping.
For i = 0 To dtSource.Rows.Count-1
If you just want to copy one DataTable to another then you can just use DataTable.Copy method.
Dim dtTemp As DataTable
dtTemp = dtSource.Copy()

Related

Datagridview not showing correct rowcount

I made a gridview where items are added and a function is called to calculate the amount
after adding a item to list i call
Private Sub totalimsum()
Dim totalsum As Double = 0
Dim totalitem As Double = 0
For i As Integer = 0 To dgvitemlist.Rows.Count - 1
totalsum += dgvitemlist.Rows(i).Cells("Total").Value
'totalitem += dgvitemlist.Rows(i).Cells("qty").Value
Next
Label16.Text = dgvitemlist.Rows.Count.ToString()
amttotal = totalsum.ToString()
txttotal.Text = amttotal
calctotal()
End Sub
it works perfect
but when a row is deleted i again call the function to recalculate the amount but it miscalculate the amount and i found that rowcount is 1 more than row present in the datagridview so i added a new function and calling it but i think it is not a solution
Private Sub totalimsumd()
Dim totalsum As Double = 0
Dim totalitem As Double = 0
For i As Integer = 0 To dgvitemlist.Rows.Count - 2
totalsum += dgvitemlist.Rows(i).Cells("Total").Value
'totalitem += dgvitemlist.Rows(i).Cells("qty").Value
Next
Label16.Text = dgvitemlist.Rows.Count.ToString()
amttotal = totalsum.ToString()
txttotal.Text = amttotal
calctotal()
End Sub
Try rebuilding the data source of the DataGridView which means you reload the contents of the DataGridView.
Or
You may try to use the dgv.update(); and dgv.refresh(); methods whenever you delete a row.

'AddRange' is not a member of... (while i attempt to save column order of a DataGridView

I'm trying to save and load the data grid view column order.
I'm using this code that i suppose is also right.
Private Sub SaveColumnOrder()
Dim upperBound As Integer = Me.DataTable1DataGridView.ColumnCount - 1
Dim columnIndexes(upperBound) As String
For index As Integer = 0 To upperBound
Dim column As DataGridViewColumn = Me.DataTable1DataGridView.Columns(index)
columnIndexes(column.DisplayIndex) = index.ToString()
Next
My.Settings.GridColumnIndexes = New StringCollection
My.Settings.GridColumnIndexes.AddRange(columnIndexes)
End Sub
Private Sub LoadColumnOrder()
Dim columnIndexes As StringCollection = My.Settings.GridColumnIndexes
For displayIndex As Integer = 0 To columnIndexes.Count - 1
Dim index As Integer = CInt(columnIndexes(displayIndex))
Me.DataTable1DataGridView.Columns(index).DisplayIndex = displayIndex
Next
End Sub
Problem is that i don't know how to set the GridColumnIndexes inside project property settings.
I set to string and other "data" options but i always get the error: 'AddRange' is not a member of... {option selected}
Which is the right option in settings to make it finally work? Thank you :)

error NullReferenceException was unhandled at progressbar

Public Sub GetStationDataFromDatabase()
Dim StationTable As New DataTable
StationTable.TableName = "Station"
Dim Counter As Integer
Dim SqlString As String
Dim OperStaRow As DataRow
Counter = 0
ProgressBar.Visible = True
ProgressBar.Minimum = 1
ProgressBar.Maximum = LocalDataSet.Tables("OR").Rows.Count
ProgressBar.Value = 1
ProgressBar.Step = 1
For Each OperStaRow In LocalDataSet.Tables("OR").Rows
SqlString = "JUST SOME STRING HERE"
ExecuteSqlCommand(SqlString, StationTable)
ProgressBar.PerformStep()
ProgressBar.Refresh()
Counter = Counter + 1
If Counter Mod 20 = 0 Then
Application.DoEvents()
End If
Next
End Sub
so, the error first happpen at progressbar.visible = True. even when i remove it, the error occur the to the line below it. can you tell me what is wrong?
and it happen when user select listbox menu. suppose i have options A and B.
i suspect that there is a typo with progressbar object name. pls check spellings. there is nothing wrong in your code.
other than that,
i suggest that you check row count > 0 before assigning progressbar maximum value.
regards

Search DataGridView for Integer Then Select Row

The below code should search DataGridView1 which is on the LeaderAccessTable form for an integer that the user inputs into SendFromID, if the DataGridView1's first column contains what the integer that the user has entered into SendFromID then the entire row should be selected. However it doesn't select any rows at all... Can anyone see why? This code is ran from a separate form.
Dim intcount As Integer
For Each Row As DataGridViewRow In LeadersAccessTable.DataGridView1.Rows
If LeadersAccessTable.DataGridView1.Rows(intcount).Cells(0).Value.ToString = SendFromID.Text Then
LeadersAccessTable.DataGridView1.Rows(intcount).Selected = True
End If
Next
MsgBox("Done.")
In the end this code worked.
Dim v_SelectRow As Integer
For counter = 0 To (LeadersAccessTable.DataGridView1.Rows.Count - 1)
For counter2 = 0 To (LeadersAccessTable.DataGridView1.Columns.Count - 1)
If (LeadersAccessTable.DataGridView1.Rows(counter).Cells(0).Value.ToString.Contains(SendFromID.Text)) Then
LeadersAccessTable.DataGridView1.Rows(counter).Cells(0).Selected = True
v_SelectRow = LeadersAccessTable.DataGridView1.CurrentRow.Index
CurrentPoints.Text = LeadersAccessTable.DataGridView1.Item(8, v_SelectRow).Value
'Do Something
Else
'Do Something
End If
Next
Next

DataGridView throwing null reference error after code update

As a fairly new user to VB.NET, I thought it was about time I tried to get to grips with DataGridView after learning the fundamentals of ListView and other basic knowledge. However, I have an error of 'Object reference not set to an instance of an object'. Let me try to explain how I think I have created this error but cannot seem to find a way out.
Initially, I had the code in the 1 winform, DGVtest.vb and upon pressing the 'fill grid' button, it filled the grid nulls and all. What I thought I would do to keep the code cleaner and in the long term, have more control, is to move the code out of DGVtest.vb and create a module, DGVmod.vb and put the code in there. However, being a new user, I now find myself totally out of my depth and looking for assistance as to how to move forward with this.
So, to outline, the DGV is in DGVtest.vb with a 'fill grid' button which calls 'DGVmod.fillgrid()' to fill the grid. If anyone can offer any assistance, I will be very grateful. Many thanks
Imports System
Imports System.Data
Imports System.Data.OleDb
Module DGVmod
Private da As OleDbDataAdapter
Private ds As DataSet
Public dtSource As DataTable
Private PageCount As Integer
Private maxRec As Integer
Private pageSize As Integer
Private currentPage As Integer
Private recNo As Integer
Sub fillPostings()
Dim conn As OleDbConnection = New OleDbConnection(My.Settings.storageConnectionString)
'Set the DataAdapter's query.
da = New OleDbDataAdapter("select * from Postings", conn)
ds = New DataSet()
' Fill the DataSet.
da.FillSchema(ds, SchemaType.Source, "Postings")
da.Fill(ds, "Postings")
' Set the source table.
dtSource = ds.Tables("Postings")
End Sub
Sub btnprevious()
If Not CheckFillButton() Then Return
If currentPage = PageCount Then
recNo = pageSize * (currentPage - 2)
End If
currentPage = currentPage - 1
'Check if you are already at the first page.
If currentPage < 1 Then
MessageBox.Show("You are at the First Page!")
currentPage = 1
Return
Else
recNo = pageSize * (currentPage - 1)
End If
loadpages()
End Sub
Sub btnnext()
'If the user did not click the "Fill Grid" button then Return
If Not CheckFillButton() Then Return
'Check if the user clicked the "Fill Grid" button.
If pageSize = 0 Then
MessageBox.Show("Set the Page Size, and then click the ""Fill Grid"" button!")
Return
End If
currentPage = currentPage + 1
If currentPage > PageCount Then
currentPage = PageCount
'Check if you are already at the last page.
If recNo = maxRec Then
MessageBox.Show("You are at the Last Page!")
Return
End If
End If
loadpages()
End Sub
Sub btnlast()
If Not CheckFillButton() Then Return
' Check if you are already at the last page.
If recNo = maxRec Then
MessageBox.Show("You are at the Last Page!")
Return
End If
currentPage = PageCount
recNo = pageSize * (currentPage - 1)
loadpages()
End Sub
Private Sub DisplayPageInfo()
DGVtest.txtDisplayPageNo.Text = "Page " & currentPage.ToString & "/ " & PageCount.ToString
End Sub
Sub fillgrid()
Try
'Set the start and max records.
pageSize = CInt(DGVtest.cmbPageSize.Text)
maxRec = DGVtest.DGV.Rows.Count
PageCount = maxRec \ pageSize
' Adjust the page number if the last page contains a partial page.
If (maxRec Mod pageSize) > 0 Then
PageCount = PageCount + 1
End If
'Initial seeings
currentPage = 1
recNo = 0
' Display the content of the current page.
loadpages()
Catch ex As Exception
MessageBox.Show(ex.InnerException.ToString)
End Try
End Sub
Private Sub loadpages()
Dim i As Integer
Dim startRec As Integer
Dim endRec As Integer
Dim dtTemp As DataTable
'Dim dr As DataRow
'Duplicate or clone the source table to create the temporary table.
dtTemp = dtSource.Clone <--- ERROR IS HERE
If currentPage = PageCount Then
endRec = maxRec
Else
endRec = pageSize * currentPage
End If
startRec = recNo
'Copy the rows from the source table to fill the temporary table.
For i = startRec To endRec - 1
dtTemp.ImportRow(dtSource.Rows(i))
recNo = recNo + 1
Next
DGVtest.DGV.DataSource = dtTemp
DisplayPageInfo()
End Sub
Sub btnfirst()
If Not CheckFillButton() Then Return
' Check if you are already at the first page.
If currentPage = 1 Then
MessageBox.Show("You are at the First Page!")
Return
End If
currentPage = 1
recNo = 0
loadpages()
End Sub
Private Function CheckFillButton() As Boolean
'Check if the user clicks the "Fill Grid" button.
If pageSize = 0 Then
MessageBox.Show("Set the Page Size, and then click the ""Fill Grid"" button!")
CheckFillButton = False
Else
CheckFillButton = True
End If
End Function
Sub cmbpage()
'Set the start and max records.
pageSize = CInt(DGVtest.cmbPageSize.Text)
maxRec = dtSource.Rows.Count
PageCount = maxRec \ pageSize
' Adjust the page number if the last page contains a partial page.
If (maxRec Mod pageSize) > 0 Then
PageCount = PageCount + 1
End If
'Initial seeings
currentPage = 1
recNo = 0
' Display the content of the current page.
loadpages()
End Sub
End Module