Compare DataTable and DataGridView and hightlight matching rows in DataGridView - vb.net

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.

Related

Won't add a default custom row on combobox

been having an issue displaying an empty item as default selected item on a combobox. This combobox is a filter for my gridview and currently my datagridview displays all data based on the first item of the combobox but what i wanted is to have an empty first combobox item so that datagridview will pull all data from database. When i run the app it says
System.ArgumentException: 'Input string was not in a correct
format.Couldn't store <> in ailment_id Column. Expected type is
Int32.'
My code to populate combobox from database:
Private Sub populateComboAilment()
data_adapter = New MySqlDataAdapter("SELECT * FROM ailment", myconnection.open())
Dim data_table As New DataTable
data_adapter.Fill(data_table)
'assign default value
Dim row As datarow = data_table.NewRow()
row(0) = ""
data_table.Rows.InsertAt(row, 0)
comboAilment.DataSource = data_table
With comboAilment
.DisplayMember = "name"
.ValueMember = "ailment_id"
End With
myconnection.close()
End Sub
Update: All is working now when I changed combobox ValueMember to a
name since it's an id before. but when I select another item it
displays nothing on the gridview because my datagridview query doesn't
know the name, only id since it's a foreign key.
Any help would be greatly appreciated!
Ah, I just looked more carefully at the code and you're not actually assigning a String containing "<>" but rather an empty String. It doesn't really matter though. A String is a String and you can't put one where a number is required. You might be able to use a String that contained digits because that could be implicitly converted to a number but a empty String doesn't qualify.
If you want an empty field in a DataRow then you need to do what ADO.NET does to represent a database null, i.e. use DBNull.Value. That means an object of type DBNull, which is required because ADO.NET predates nullable value types. You can't just use Nothing because would work for reference types but not value types, e.g. if you assign Nothing to an Integer variable you are effectively setting it to zero.
In short, you need to change this:
Dim row As datarow = data_table.NewRow()
row(0) = DBNull.Value
row(1) = DBNull.Value
data_table.Rows.InsertAt(row, 0)
In the case of the name column, its data type is String so you could use an empty String there (preferably String.Empty rather than "" but either works) but null is more appropriate because it is actually no value, rather than a value containing no characters.

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

Runtime error 91: object variable or with block variable not set

I'm running a macro in Word which, among other things, adds a line to the bottom of a table already existing in the document and fills certain cells. The odd thing is that for the majority of the documents it Works, however there are a couple of documents for which I receive the Run Time error 91.
'Update the document properties, updates the header, updates the table of contents,
' and adds a file to the Version History table.
Sub zzAddVersionHistory(strUsuario As String, strDescripcion As String)
Dim newDate As String
Dim rowNumber As Integer
Dim rowNew As Row
Dim strIssue As String
Dim ascIssue As Integer
'Updates the Date property
newDate = Format(Date, "dd/MM/yyyy")
ActiveDocument.CustomDocumentProperties("Date").Value = newDate
'Finds the version from the Issue property and updates the version
If DocPropertyExists("Issue") = True Then
strIssue = ActiveDocument.CustomDocumentProperties("Issue").Value
ascIssue = (Asc(strIssue)) + 1 'Convierte el Issue en ascii y le suma uno
strIssue = Chr(ascIssue) 'Convierte el ascii en caracter
ActiveDocument.CustomDocumentProperties("Issue").Value = strIssue
End If
'Updates Header and footer
zzActualizarHeaderFooter
'Updates Fields
zzActualizarCampos
'Accepts changes in header y footer
zzAcceptChangesInHeaderFooter
'Adds a row to the table
rowNumber = Application.ActiveDocument.Tables(1).Rows.Count
Set rowNew = Application.ActiveDocument.Tables(1).Rows.Add
'Inserts KTC Issue In first cell of the new row
rowNew.Cells(1).Range.InsertAfter (strIssue) ''' Runtime-error here
'Inserts Issued By in the third cell of the new row
rowNew.Cells(3).Range.InsertAfter (strUsuario)
'Inserts the Date in the fourth cell of the new row
rowNew.Cells(4).Range.InsertAfter (newDate)
'Inserts Description of Changes in the fifth cell of the new row
rowNew.Cells(5).Range.InsertAfter (strDescripcion)
'Updates the Table of Contents
zzActualizarIndices
End Sub
If needed I can provide the subs and functions called by the macro, but I don't think they have anything to do with the issue.
I believe the problem is somewhere in those documents, in the table format, but I could not find an explanation anywhere nor I can find any difference with the tables in other documents.
Nested tables mess up the cells collection. Once you manually merge/split cells on the last row and then add a new row, things become... different. Save as rtf, look at the code, and scratch your head.
Use one (the first? second?) "standard" row to count the columns and adjust the code in case the column count / cells count of the last row differs from that "norm". Use "Selection" and a breakpoint to investigate the troublesome table to learn how to handle these special cases.

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 search in and edit Table by using DataGridView

I have a SQL database with a table "Employees" in it (with large number of rows). By using DataGridView, I want to search for specific "Employee's Name" and change it's "Job". How can I achieve that. I'm using VB.net. Please Help Me.
Not sure if this will help but write a loop that goes through all the values if it finds a match its true if not it is false ,if found the item can be displayed in a textbox and edited
if not a message is displayed saying "no match found"
the editing part can be done using a procedure that will update the value in your grid with what is entered
i can supply code for this if need be but i am unsure if this is what you wish
and there is most likely a better way of doing it
you can loop through your grid, and check if the data you wish to edit exists using the For loop:
Supposing you are using a textbox as the input, and you use a label to hold the employee ID:
Dim EmpIDColumn as Integer = 'array number of your EmpID Column
Dim EmpNameColumn as Integer = 'The array number of the column where your EmpName is
Dim JobColumn as Integer = 'The array number of your job column
For each dr as Datagridviewrow in Datagridview1.Rows
If dr.cells(EmpNameColumn).value = TxtSearchBox.text Then
txtEmpJob.text = dr.cells(JobColumn).value
lblEmpID.Text = dr.cells(EmpIDColumn).value
End if
Next
Okay, so you've searched the record successfully. Next step (after editing the job, and even other details like the name) would be to update the record in the grid. Remember you set the lblEmpID's text to empID in the column? Use it to find the
Record you wish to change in the grid using the same technique above!
Dim EmpIDColumn as Integer = 'array number of your EmpID Column
Dim EmpNameColumn as Integer = 'The array number of the column where your EmpName is
Dim JobColumn as Integer = 'The array number of your job column
For each dr as Datagridviewrow in Datagridview1.Rows
If dr.cells(EmpIDColumn).value = lblEmpID.text Then
dr.cells(JobColumn).value = txtEmpJob.text
dr.cells(EmpNameColumn).value = txtEmpName.text
'then, type in here your SQL Query Update!
End if
Next