How to delete empty datagridview cells on import - vb.net

Currently I have my program hiding blank or empty datagridview cells. I want to find a way to delete these cells entirely. The reason being, after the blank cells were hidden they would reappear after going through some of my other validations. These validations checked to see if the cells contained any invalid input such as negative numbers,non-numeric input and blank cells. If they contained any of the above they would be populated with default values, thus making my hidden cells reappear. Hopefully if there is a way to delete these cells they won't have a change of getting filled with default data. I've found the below code on MSDN but it doens't seem to work properly for whatever reason. Also I'm using the DATABINDINGCOMPLETE event. I'm not sure if there is another event that would work better for this situation. I greatly appreciate any help you may give!
Private Sub DataGridView1_DataBindingComplete(sender As Object, e As DataGridViewBindingCompleteEventArgs) Handles DataGridView1.DataBindingComplete
Dim i As Integer = 0
Dim mtCell As Integer = 0
For Each row As DataGridViewRow In DataGridView1.Rows
For j = 1 To row.Cells.Count -2
If row.Cells(j).Value Is DBNull.Value Then
mtCell += 1
End If
Next
If mtCell = row.Cells.Count Then
DataGridView1.Rows.RemoveAt(i)
End If
i += 1
mtCell = 0
Next
end sub

There are various problems with your code. Here you have an improved version which should work without any problem:
Dim mtCell As Integer = 0
Dim row As DataGridViewRow = New DataGridViewRow()
For rowNo As Integer = DataGridView1.Rows.Count - 2 To 0 Step -1
row = DataGridView1.Rows(rowNo)
Try
For j = 0 To row.Cells.Count - 2
If row.Cells(j).Value Is Nothing OrElse row.Cells(j).Value Is DBNull.Value Then
mtCell += 1
End If
Next
If mtCell = row.Cells.Count - 1 Then 'I understand that you want to delete the row ONLY if all its cells are null
DataGridView1.Rows.RemoveAt(rowNo)
End If
mtCell = 0
Catch ex As Exception
Exit For
End Try
Next rowNo
First thing, it is better to iterate the Collection "backwards" when deleting in order to avoid problems (example: 3 rows; you delete the first position and the loop goes to the second one; but after the deletion all the rows "move up" and thus the second position is now occupied by the third row -> you would skip the second row and, eventually, iterate beyond the limits of the Collection). DBNull.Value is quite restrictive; not sure if it is working fine under your specific conditions, but better complementing it with Nothing. You cannot affect the item being iterated in a For Each loop (unlikely in a normal For one); in this case you are affecting it indirectly but just to make sure, better relying on a normal For loop. You are iterating through rows but you are not deleting these rows, but the ones defined by a counter (i) which is not necessarily related to the current row number, better getting rid of it. Lastly I have included a try...catch to make sure (that you don't access an inexistent position).

Related

InvalidArgument=Value of ' ' is not valid for 'index' (' ' inside number)

This is my first question. I can't solve this error for 2 weeks.
In order to solve the problem signed up.
This is my vb code.
Try
For i As Integer = 0 To ListBox1.Items.Count - 1 Step 1
For j As Integer = 0 To ListBox2.Items.Count - 1 Step 1
If ListBox1.Items(i).ToString().Equals(ListBox2.Items(j).ToString()) = True Then
ListBox1.Items.RemoveAt(i)
End If
Next
Next
Catch ex As Exception
MsgBox("LOAD ERROR: " + ex.Message, vbCritical, "ERROR")
End Try
error :
InvalidArgument=Value of '20' is not valid for 'index'(' ' is varient.)
Project has no problems except for this error
Try this:
Dim items = ListBox1.Items.Where(Function(item) ListBox2.Items.Contains(item)).ToList()
For Each item in items
ListBox1.Remove(item)
Next
When I run your code, I receive a different exception, argument out of range...and that is caused by deleting items from an indexed collection while you're iterating through it. For example, let's say listbox1 has 10 items in it. If you find item number 1 in listbox2 and delete it, now you only have 9 items left in listbox1. The problem is, when you entered your loop, you told it to loop 10 items, and it will still try to do that. At some point, if any items are deleted, this loop will throw an exception...so you will need to change that sooner or later. To mitigate this, step through the collection that you'll be deleting items from backward like this:
For i As Integer = ListBox1.Items.Count - 1 to 0 Step -1
When I run the code with the change shown above, it works as intended and removes the duplicate items from listbox1. Unfortunately, I was unable to reproduce your invalid argument exception. It's odd to see that because usually that exception likes to pop up when using listviews, not listboxes. Perhaps you can edit your post and add a screenshot of the data in your listboxes so it's easier for other people to troubleshoot.
As you remove items from ListBox1 the total item count will decrease (obviously), however the For loop does not respect that. A For loop will only have the right side of To set once, which is done prior to the first iteration.
What you're currently doing is actually equal to this:
Dim a As Integer = ListBox1.Items.Count - 1
For i As Integer = 0 To a Step 1
Dim b As Integer = ListBox2.Items.Count - 1
For j As Integer = 0 To b Step 1
...
Next
Next
The fix for this is simple; create a variable that holds how many items you have removed, then, in an If-statement, check if i is more or equal to the current item count subtracted with how many item's you've removed. If so, exit the loop.
Dim ItemsRemoved As Integer = 0
For i As Integer = 0 To ListBox1.Items.Count - 1 Step 1
If i >= ListBox1.Items.Count - ItemsRemoved Then Exit For
For j As Integer = 0 To ListBox2.Items.Count - 1 Step 1
If ListBox1.Items(i).ToString().Equals(ListBox2.Items(j).ToString()) = True Then
ListBox1.Items.RemoveAt(i)
End If
Next
Next
For future reference you should also always remove/comment out the Try/Catch-statement so you can see where the error occurs and get more detail about it.
The point of my answer is that when you iterating any collection, you should NOT try to modify this collection. In for-loops you run into such trouble. But you can iterate using while-loop with no issues
Try
Dim index As Integer = 0
While index < ListBox1.Items.Count '!! this code based on fact that ListBox1 item Count changes
For j As Integer = 0 To ListBox2.Items.Count - 1 ' <- this is ok because ListBox2 doesn't chage
If string.Equals(ListBox1.Items(index).ToString(), ListBox2.Items(j).ToString()) Then
ListBox1.Items.RemoveAt(index)
Continue While ' no index increase here because if you remove item N, next item become item N
End If
Next
index += 1
End While
Catch ex As Exception
MsgBox("LOAD ERROR: " + ex.Message, vbCritical, "ERROR")
End Try
This is good example of how things actually work. And it shows few techniques
I just selected Build-->Clean solution and it cleaned out the bad elements. This occurred as a result of adding and deleting menu items, without deleting the subroutines of the deleted menu items. As soon as I cleaned the solution, and then ran the project, the error was gone.

Prevent Vertically Merged Cells from Breaking Across Page - Automatically

I have to create documents that have large tables of data copied into them from Excel. The tables can be hundreds of rows long and generally ~20 columns wide. Many of the columns have been merged vertically to enhance readability and group sets of data.
I have been able to write a macro that will fully format the entire table, except I have not been able to figure out how to automatically prevent the Vertically Merged cells from breaking/splitting across multiple pages. To do it manually, you select all of the rows in the merger except for the last one and then you turn on "Keep With Next" in the paragraph settings. I thought this would be easy to do, but you can not access individual rows in VBA if there are any vertically merged cells in the table.
Does anyone have an idea how to automatically go through the rows and set the "Keep With Next" property for groups of rows that have been merged together?
Here is an example of how Word normally handles vertically merged cells across tables:
This is how I would like it to look, with doing all the work manually:
Yes, working with merged cells in Word (and Excel for that matter) is quite annoying.
This can be done, though, by accessing individual cells in table. I have written the following Sub Routine below that should work for you. I assumed that you had at least one column with no vertically merged cells in it and that you only had one column that controlled the length of the merged block. Although adding more controlling columns should be easy.
Sub MergedWithNext() 'FTable As Table)
Dim Tester As String
Dim FTable As Table
Dim i As Integer
Dim imax As Integer
Dim RowStart As Integer
Dim RowEnd As Integer
Dim CNMerged As Integer
Dim CNNotMerged As Integer
Dim CNMax As Integer
CNMerged = 2 'A column number that is vertically merged that you don't want to split pages
CNNotMerged = 1 'A column number that has no vertical mergers
Set FTable = Selection.Tables(1)
With FTable
imax = .Rows.Count
CNMax = .Columns.Count
'Start with no rows kept with next
ActiveDocument.Range(Start:=.Cell(1, 1).Range.Start, _
End:=.Cell(imax, CNMax).Range.End).ParagraphFormat.KeepWithNext = False
On Error Resume Next
For i = 2 To imax 'Assume table has header
Tester = .Cell(i, CNMerged).Range.Text 'Test to see if cell exists
If Err.Number = 0 Then 'Only the first row in the merged cell will exist, others will not
'If you are back in this If statement, then you have left the previous block of rows
'even if that was a block of one. The next If statement checks to see if the previous
'row block had more than one row. If so it applies the "KeepWithNext" property
If (RowEnd = (i - 1)) Then
'.Cell(RowStart, 1).Range.ParagraphFormat.KeepWithNext = True
ActiveDocument.Range(Start:=.Cell(RowStart, CNNotMerged).Range.Start, _
End:=.Cell(RowEnd - 1, CNNotMerged).Range.End).ParagraphFormat.KeepWithNext = True
'Use RowEnd - 1 because you don't care if the whole merged block stays with the next
'row that is not part of the merger block
End If
RowStart = i 'Beginning of a possible merger block
RowEnd = 0 'Reset to 0, not really needed, used for clarity
Else
RowEnd = i 'This variable will be used to determine the last merged row
Err.Clear
End If
If i = imax Then 'Last Row
If (RowStart <> imax) Then
ActiveDocument.Range(Start:=.Cell(RowStart, CNNotMerged).Range.Start, _
End:=.Cell(imax - 1, CNNotMerged).Range.End).ParagraphFormat.KeepWithNext = True
'Use imax - 1 because you don't care if the whole merged block stays with the next
'row that is not part of the merger block
End If
End If
Next i
On Error GoTo 0
End With
End Sub
This code will loop through each row in the table, excluding the header, looking for vertically merged cells. Once it finds a block, it will assign the "Keep With Next" property to each row in the block, except for the last row.

DataGridView Copy a selected row issue

I have a datagridview and i want to copy the exact row that gets selected by the user to the same position (above). I have it right now so it inserts the line above the current line that is selected but it is not copying all the values.
I'm just using a basic grid, no dataset or datatables. heres my code.
If dgvPcPrevMonth.SelectedRows.Count > 0 Then
dgvPcPrevMonth.Rows.Insert(dgvPcPrevMonth.CurrentCell.RowIndex, dgvPcPrevMonth.SelectedRows(0).Clone)
Else
MessageBox.Show("Select a row before you copy")
End If
The clone method only clones the row, not the data in it. You'll have to loop through the columns and add the values yourself after inserting it
Public Function CloneWithValues(ByVal row As DataGridViewRow) _
As DataGridViewRow
CloneWithValues = CType(row.Clone(), DataGridViewRow)
For index As Int32 = 0 To row.Cells.Count - 1
CloneWithValues.Cells(index).Value = row.Cells(index).Value
Next
End Function
The code is taken directly from the msdn link provided below
https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewrow.clone(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1
I updated your code to test if current row was not the first and to clone the cuurent row (not the first one).
If ddgvPcPrevMonth.CurrentCell.RowIndex > 0 Then
dgvPcPrevMonth.Rows.Insert(dgvPcPrevMonth.CurrentCell.RowIndex, dgvPcPrevMonth.Rows(dgvPcPrevMonth.CurrentCell.RowIndex-1).Clone)
Else
MessageBox.Show("Select a row (but not the first one) before you copy")
End If

Allow only specific value range in DataGridView Columns' cells

I am moving along, albeit slowly, with this project. I have my DataGridView almost set to where I can proceed to the next section of the project. But one last thing that I have found that I need to fix:
Problem
I need to limit the range of values that a user can enter into each column of the DGV. For instance:
columns 0 and 1 can accept values between 0-3000
column 2 can accept values between 0-20000
column 3 (0-1000)
column 4 (0-320)
The DGV does not have a set number of rows as a user can add as many rows as they need with a click of a button. I have seen examples showing similar code for setting the values range in the entire DGV or even the rows, but I have not been able to find anything or help showing how to set the range values for each column.
I have some code written for cell validating to ensure that only Integer values are entered into the DGV and that no cells are empty. Is there a way to add to this code or modify it to also remedy my current problem? If so, can someone provide some help to get me started? - Thank you, Newbie.
Private Sub LftMtr_Data_Grid_CellValidating(ByVal sender As Object, _
ByVal e _
As DataGridViewCellValidatingEventArgs) _
Handles LftMtr_Data_Grid.CellValidating
Me.LftMtr_Data_Grid.Rows(e.RowIndex).ErrorText = ""
Dim newInteger As Integer
' Don't try to validate the 'new row' until finished
' editing since there
' is not any point in validating its initial value.
If LftMtr_Data_Grid.Rows(e.RowIndex).IsNewRow Then Return
If Not Integer.TryParse(e.FormattedValue.ToString(), newInteger) _
OrElse newInteger < 0 Then
e.Cancel = True
Me.LftMtr_Data_Grid.Rows(e.RowIndex).ErrorText = "Cells must not be null and must equal a non-negative integer"
End If
End Sub
Seeing that your validation is virtually the same as seen here in MSDN documentation, I trust you understand what all is happening. Note that the cell row index is accessed in the method. The same can be done for the column index. Since you want to validate the upper limit of cell values based on column, we will use this column index to set the upper limit to check against.
Try adding the following code after Dim newInteger As Integer but before your If statement:
Dim upperLimit As Integer = 0
Select Case e.ColumnIndex
Case 0, 1
upperLimit = 3000
Case 2
upperLimit = 20000
Case 3
upperLimit = 1000
Case 4
upperLimit = 320
Case Else
Debug.WriteLine("You decide what should happen here...")
End Select
Lastly, modify your If statement:
If Not Integer.TryParse(e.FormattedValue.ToString(), newInteger) _
OrElse newInteger < 0
OrElse newInteger > upperLimit Then
This should ensure each cell checked stays within its column's accepted value range.

For Loop to count checked items on datagrid not counting correctly

I worked out the following loop to count and display how many rows on my datagrid are checked. However, the loop is ignoring my first checked row. The count does not start at 1 until I have checked the second row. The same happens when I uncheck, the values are off by one.
Dim chkRowCount As Integer = 0
For Each row As DataGridViewRow In dgvAssignGridView.Rows
If row.Cells(6).Value = True Then
chkRowCount += 1
Else
chkRowCount += 0
End If
Next
lblChkCount.Text = chkRowCount.ToString
I have tried setting the variable to 1 instead of 0, but that had some unwanted results.
I am guessing you have this code in CellContentClick. The problem is that the code in that routine fires before the value of the checkbox is actually changed. However, you can basically force the DataGridView to verify itself first by putting the following line right before your code.
dgvAssignGridView.EndEdit()
That forces the cell click to register before you do your count.