DataGridView Copy a selected row issue - vb.net

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

Related

DataGridView Select Row with Specific Cell value [VB.NET]

I am using this code to move the row selection programmatically
For Each row In DataGridView1.Rows()
If row.Cells(0).Value.ToString().Equals(code) Then
row.Selected = True
End If
Exit For
Next
But the Problem I am facing is This only Changes the highlighted row but doesn't actually select the row..
When I try to get data from selected row it gives data from previous row not the blue highlighted row.
Actually Row header Tick type thing doesn't move It stays on previous row.
You also have to set the selceted cell:
For Each row As DataGridViewRow In DataGridView1.Rows()
If row.Cells(0).Value.ToString().Equals(code) Then
row.Selected = True
DataGridView1.CurrentCell = row.Cells(0)
Exit For
End If
Next
The reason your code works only for the first row is that Exit For was outside the If statement. If you include it the code works like a charm.

Compare DataTable and DataGridView and hightlight matching rows in DataGridView

I have a database table which contains a list of usernames and their current active location, an integer called SEQUENCE.
I get this list of sequence numbers into a datatable with a single column (e.g. "SELECT SEQUENCE FROM TABLE"):
dtUsers = CLS_USERS.GetUsers(User)
It excludes the current user, which is why I parse in User.
What I then do is loop through the datatable and for each number I want to set the matching row in a datagridview (which also has a SEQUENCE column) to a different colour. This is my current code:
For Each row As DataRow In dtUsers.Rows
intSeq = row("SEQUENCE")
For Each dgv_row As DataGridViewRow In dgvCandList.Rows
If dgv_row.Cells("CURRENT_SQ").Value = intSeq Then
dgv_row.DefaultCellStyle.BackColor = Color.Cyan
Else
dgv_row.DefaultCellStyle.BackColor = Color.Grey
End If
Next
Next
However, all rows are highlighted rather than just those where dgv_row.Cells("SV_CURRENT_CAND_SQ").Value = intSeq is True... I've verified that this loop is working correctly, so it must be dgv_row.DefaultCellStyle.BackColor = Color.Cyan which is incorrect?
If so, how should I correctly be assigning the row back colour of specific DataGridRow?
EDIT: This code works correctly, my issue was related to bug outside this loop causing the BackColor to be sent for everything, and then never setback to default if where BackColor wasn't being set back to the default if it wasn't in dtUsers.

code will not advance the row count, such that the data will print on subsequent rows

I am trying (using VB) to copy 7 values from 1 location to another.
(copy from F115 to F134.)
(F115 is source of numbers; F134 is destination for numbers)
If there is data (any data) in F134 I want to advance the row by 1 and then print/copy. I do not want to overwrite any lines of data.
So, if there is data in the first row (F134) then I want to move/advance the row count by 1 and then copy the values into row F135 - and so on. It's possible that there could be 500 to 100 rows of numbers and I need to be able to view all of this data.
So far, this is the code I have: some works, but it does NOT advance the row count and continues to print into Cell F134. (oh yes, F124 is just a set of empty cells.)
Ok, this is my code;
Sub dbtest4()
Dim RowCounter As Integer
rowCounter = 1
Do Until rowCounter = rowCounter +1
'trying to advance the row counter by 1 such that if there is data in F134, the line count will advance and the new data will print into the NEXT line. (which would be F135)
'the following code probably is unnecessary, but I'm trying anything...
'actually the following code works ok: Range("F134").Resize(1,7).Value = Range("F115").Resize(1,7).Value, but that's about it.
If Range ("F134") = 0 then
Range("F134").Resize(1,7).Value = Range("F115").Resize(1,7).Value
'trying to print data cells from F124 if there is no data in F134
Else
Range("F134"),Resize(1,7).Value = Range("F124).Resize(1,7).Value
'trying to print the zeros or blank numbers from F115 if F134 has data in it
End if
Loop
Exit Do
End Sub
Thanks to anyone who may be able to offer some assistance.
So right now the exit condition for the Do While loop is that rowCounter has to increment by one. I can't see a reason why this should fail and that is why it is only happening once. Here is some psuedocode:
Do Until copiedVals = 7 'Or whatever exit value you want
If row.Value.Exists() then
'There is a value in this row, so increment the row count
rowCounter = rowCounter + 1
Else
'This row is empty and you can do your thing
'rowCounter will have the current row value
copiedVals = copiedVals + 1
End If
End Loop

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.

How to delete empty datagridview cells on import

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