Compare values with 3 states Y/N as String or DbNull - vb.net

I have database table with a column DECISION which can have the following values:'Y','N', or (null). There can be multiple people updating the values in this database table via an application.
I want to ensure that the DataGridView which displays this information is kept up to date for all users regularly.
I have a background thread which does the following:
For Each new_row As DataRow In dsData.Tables("Progress").Rows
For Each cur_row As DataRow In dsData.Tables("List").Rows
If new_row("SEQ") = cur_row("SEQ") And new_row("DECISION") <> cur_row("DECISION") Then
cur_row("DECISION") = new_row("DECISION")
End If
Next
Next
Essentially dsData.Tables("Progress") is populated with the latest data and then compared to the current values in the DataGridView column, based on a sequence number SEQ.
What I want to happen is that if they are different, the cur_row value is changed to that of new_row.
However, it falls over because sometimes it tries to compare a string 'N' or 'Y' with (null) which can't be done.
What is the best way to work around this?
I do want to compare and update any (null) as it is a genuine state in this system.

The TryCast operator can help you here. You can try to cast as type String and a field containing DBNull.Value will simply return Nothing.
Dim cur_val = TryCast(cur_row("DECISION"), String)
Dim new_val = TryCast(new_row("DECISION"), String)
If new_val IsNot Nothing AndAlso cur_val <> new_val Then
cur_row("DECISION") = new_val
End If

Related

Determine if an integer is a member of a list of integers

I need to determine if a particular integer does not exists in a datagridview column. I assume I should create an array of the integers from the dgv column, and then compare if the integer exists in the array. However, there is perhaps an easier or simpler way.
I have looked at many articles but none of them resolve my task. Some of the Stack Overflow articles show similar solutions but I can't quite determine what to do.
For a = 0 To Dgv1.RowCount - 1
If Not Dgv1(1, a).Value = Dgv0(1, m).Value Then
Dgv0(1, Dgv0.RowCount - 1).Value = Dgv0(1, m).Value
End If
Next
I hope to compare an integer with a column of integers in a datagridview and if it is present do nothing but if is not present add it to the datagrid view
Are you using wpf? If yes, create a model.
provide a checking mechanism at the setter, use observablecollection or list then bind it to the datagirdview
Get the row and column of the datagridview
then compare (means condtional statement) to the variable you wanna check
and of course it should be inside of loop, loop count is equal to the count of rows you have in the datagridview.
Here's an example code:
Dim column As String = "YourColumnNameHere"
' Assuming 2 is the number you wanna compare
Dim value As Integer = 2
For row As integer = 0 to dataGridView.RowCount - 1
If dataGridView.Rows(row).Cells(column).Value = value Then
' Do something here
Else
' Do something here
End If
Next

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.

vb.net - Sort datagridview column numerically

I know this has been asked quite a few times, but i'm having issues with the solutions found on most other pages.
I have a single datagridview column that i want to be sorted by number (1,2,10 instead of 1,10,2)
Best i can see online, i need to convert the column or cell to an integer value type - but i'm not sure how to do so.
I've tried grid.columns(4).valuetype = typeof(System.int32), and tried the same for cells individually.
Trying above always results in a "int32 is a type in 'system' and cannot be used as an expression" error - which i'm not sure about.
The data itself is obtained froma text file, and converted from string to integer when being added into the cell datagrid_alltracks.Rows(shutupaboutlambda).Cells(4).Value = CInt(numstring))
You can just set the DataGridView SortCompare Event to compare two integers (or two singles, or two doubles). Code wise (calling your datagridview "grid")
Private Sub grid_SortCompare(sender as Object, e as DataGridViewSortCompareEventArgs) Handles grid.SortCompare
e.SortResult = CInt(e.cellvalue1).CompareTo(CInt(e.cellValue2))
e.Handled = True
End Sub
if you are doing single or double variables, use CSng or CDbl instead of CInt
e.SortResult = CSng(e.cellvalue1).Compareto(CSng(e.CellValue2)
You can do more fancy sorting if you want, You basically need to know that e.SortResult is Positive, Negative or Zero, and your cells are sorted according to that result (Positive keep order, negative reverse order, Zero - matched - do nothing (yet)). The current row index(s) and column are available in the e arguments so you can also compare adjacent column data if the current cells are matched)
If the grid is bound to a data source you could try
datatable.Columns.Add("ColumnName", GetType(Integer))
Else you may need to use the SortCompare event on the gridview.
See here
I know I'm coming to the party late, but I found that I once I had added the data, I needed to convert the desired columns to have a data type.
I'm adding data like the following:
DataGridView1.Rows.Add(New String() {CInt(recordnum), True, "play", wszName.ToString, qiOffset.ToString, value.ToString, qiLength.ToString})
Then, after all the data has been added, I then do a simple loop and convert the column, where I can then sort it. It's set up so you can do multiple columns if need be.
Dim colnum As Integer
colnum = 0 ' set this as your column to change the data type to
For i As Integer = 0 To DataGridView1.Rows.Count - 1
Dim d As Double = Double.Parse(DataGridView1.Rows(i).Cells(colnum).Value.ToString())
DataGridView1.Rows(i).Cells(colnum).Value = CInt(d)
DataGridView1.Rows(i).Cells(colnum).ValueType = GetType(Double)
Next
Sorting can work for whatever column you adjusted. In this case, it's column 4.
DataGridView1.Sort(DataGridView1.Columns(4), System.ComponentModel.ListSortDirection.Ascending)

Comparing one dataset to another dataset in vb.net

I have two data set in my code. I need to compare that second data set
with first data set My first data set returns this result below:-
FirstDs:-
MaxUpdatedPrepped MaxUpdatedSent MaxUpdatedStamped
1900-01-01 1900-01-01 1900-01-01
And my second data set returns below:-
SecondDS:-
MaxUpdatedPrepped MaxUpdatedSent MaxUpdatedStamped
1900-01-01 1900-01-01 2014-11-11
I need to compare that both result and return alert like "Not matched" if the both first data set value is not match with second data set value. I tried a lot but i could get only wrong answer
For i As Integer = 0 To DsMaxDates1.Tables(0).Rows.Count - 1
Dim found As Boolean = False
For j As Integer = 0 To ds.Tables(0).Rows.Count - 1
If DsMaxDates1.Tables(0).Rows(i)(0).ToString = ds.Tables(0).Rows(j)(0).ToString Then
found = True
End If
Next
If found = False Then
ASPNET_MsgBox("Another User Working in Same Account. Please Click Reset.")
End If
Next
This above result returns true instead of false.
You should never change the type of your data unless it's absolutely necessary. Treat dates as Date, integers as Integer, strings as String, decimals as Decimal, etc. The ToString method is mostly used when you want to display the data to the user.
With that being said, you're not comparing datasets, you're comparing datatables.
The reason as to why it returns True is because you only compare the first column. You need to compare all the columns. If your table doesn't contain complex data types like byte arrays then the simplest way is to use LINQ combined with Enumerable.SequenceEqual.
The following code assumes that each table contains the same number of rows and columns.
''Uncomment to unleash the one-liner:
'Dim notEqual As Boolean = (From i As Integer In Enumerable.Range(0, DsMaxDates1.Tables(0).Rows.Count) Where (Not DsMaxDates1.Tables(0).Rows(i).ItemArray.SequenceEqual(ds.Tables(0).Rows(i).ItemArray)) Select True).FirstOrDefault()
Dim notEqual As Boolean = (
From i As Integer In Enumerable.Range(0, DsMaxDates1.Tables(0).Rows.Count)
Where (Not DsMaxDates1.Tables(0).Rows(i).ItemArray.SequenceEqual(ds.Tables(0).Rows(i).ItemArray))
Select True
).FirstOrDefault()
If (notEqual) Then
ASPNET_MsgBox("Another User Working in Same Account. Please Click Reset.")
End If
You can expand this even further by creating a reusable extension method:
Public Module Extensions
<System.Runtime.CompilerServices.Extension()>
Public Function SequenceEqual(table1 As DataTable, table2 As DataTable) As Boolean
Return (((((Not table1 Is Nothing) AndAlso (Not table2 Is Nothing))) AndAlso ((table1.Rows.Count = table2.Rows.Count) AndAlso (table1.Columns.Count = table2.Columns.Count))) AndAlso ((table1.Rows.Count = 0) OrElse (Not (From i As Integer In Enumerable.Range(0, table1.Rows.Count) Where (Not table1.Rows(i).ItemArray.SequenceEqual(table2.Rows(i).ItemArray)) Select True).FirstOrDefault())))
End Function
End Module
Then you can simply do as follows:
If (Not DsMaxDates1.Tables(0).SequenceEqual(ds.Tables(0))) Then
ASPNET_MsgBox("Another User Working in Same Account. Please Click Reset.")
End If

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