Checking duplicate Values on DataGrid - vb.net

I have a DataGrid which is bound with a DataTable having two columns which store sequences, in my DataGrid these sequence columns are bound with DataGridViewComboBoxes. User is able to set sequence from ComboBoxes. Default values in sequence columns is 0.
I just want to check duplicacy in both the columns on button click, user should not be able select any duplicate value in both the columns.
If i implement it by using ToTable method of DataView to find distinct values it also takes rows with value "0"
if i implement unique constraint on column on DataTable it also checks for 0.
If try to remove values with 0 it also changes DataGrid As DataGrid is bound with DataTable
If i try to declare a new DataTable from existing dataTable it also gets bound to DataGrid Automatically.
Please help me.

Here is an example of how you can check for duplicate values in a DataTable:
Option Strict On
Module Module1
Sub Main()
Dim dt As New DataTable
dt.Columns.Add("mycolumn", GetType(Integer))
dt.Rows.Add({"1"})
dt.Rows.Add({"2"})
dt.Rows.Add({"2"})
dt.Rows.Add({"4"})
dt.Rows.Add({"7"})
Dim duplicateDictionary As New Dictionary(Of Integer, Integer) 'value, count
For Each row As DataRow In dt.Rows
Dim count As Integer = 0
Dim value As Integer = CInt(row("mycolumn"))
duplicateDictionary.TryGetValue(value, count)
duplicateDictionary(value) = count + 1
Next
For Each kv As KeyValuePair(Of Integer, Integer) In duplicateDictionary
If kv.Value > 1 Then 'we have a duplicate
Debug.WriteLine("{0} is a duplicated value, encountered {1} times", kv.Key, kv.Value)
End If
Next
End Sub
End Module
Adding a UniqueConstraint is possible as well, but I find it too intrusive at times, depending on how your editing works. For direct in-grid editing, you may want the user to save a non-valid record in memory, and allow to fix the error, showing validation errors instead of constraint violation exception. Of course you never save invalid data to the database.

Related

Dataset with Datatable

I am trying to check if my dictionary contains values in my dataset.datatable and if its quantities in the second column of the dataset are less than or greater than the quantities in my datatable. I tried using the SELECT method but it doesn’t seem to work, I get the error BC30469 reference to non-shared member requires object reference?
I was just trying to do a simple search in the table first to see if I can even do that..... apparently not. Thanks for the help!
Dim row As DataRow = DataSet.DataTable.Select("ColumnName1 = 'value3'")
If Not row Is Nothing Then
searchedValue = row.Item("ColumnName2")
End If
You could get a dictionary to compare with the one you already have like this (assuming your key is a string and the amount an Int32 and that your dataset contains only one table):
Dim myDBDict As Dictionary(Of String, Int32) =
From e In myDataSet.Tables(0).Rows.Cast(Of DataRow).ToDictionary(Of String, Int32)(
Function(e) e.Field(Of String)("MyIDColumn"),
Function(e) e.Field(Of Int32)("myAmountColumn"))

How to iterate display values in a combobox

I have a combobox whose values (displayvalue) are formatted (from a database query):
John Doe (11111)
where 11111 is the userID. The UserID is the login name for their machine and I want to default the selected value to the login UserID.
Since combobox.findstring(UserID) only matches if the entry begins with that string, I need to iterate through the values to look for the substring of UserID in the entries.
I've searched around here, but solutions seems to land all around this specific example. I can't seem to find a method that returns the display value at a specific index. What am I missing?
EDIT:
This is how I am populating my combobox:
Private Sub PopulateDropdown(strSQl As String, objControl As ComboBox, strTextField As String, strDataField As String)
Dim objdatareader As New DataTable
objdatareader = DataAccess.GetDataTable(strSQl)
objControl.DataSource = objdatareader
objControl.DisplayMember = strTextField
objControl.ValueMember = strDataField
End Sub
This may actually help folks trying to find the ValueMember of a combobox as well.
I am populating my combobox from a datatable, so this solution may only be valid from that. I am not really sure why this works. I just stumbled upon it.
First, I started by doing a for each item in combobox.items. According to intelisense, there is no property of .value, .text, .DisplayMember, or anything related to that. I did notice that the return type on combobox.items is a DataRowView. I am not sure why that is, but I went with it. One of the members of DataRowView is Row. It turns out, each column from the DataTable is added to the Row collection in 'item's' DataRowView. Rows(0) is the first column, Row(1) is the second, etc. I was then able to look in the Row's full text to find my userid, and then select that row by using the FindExactString of the combobox. The below code works (I built the datatable manually in this example):
dim UserID As String="12345"
dim MyTable as New Datatable
MyTable.Columns.Add("Value", Type.GetType("System.String"))
MyTable.Columns.Add("Text", Type.GetType("System.String"))
MyTable.rows.add("1","Bob Smith(11223)"
MyTable.rows.add("2","George Brown(12345)"
cboAssignedID.datasource=MyTable
cboAssignedID.DisplayMember="Text"
cboAssignedID.ValueMember="Value"
For Each item In cboAssignedID.Items
If InStr(item.Row(1).ToString, UserID) > 0 Then
cboAssignedID.SelectedIndex = cboAssignedID.FindStringExact(item.Row(1).ToString)
End If
Next

Remove A Row From A List Of DataRow

I am using a Dictionary to create a key to a List Of DataRow. I want to iterate through each key and remove rows in the List. This will throw an out of range exception when I explicitly try to remove a row. How can I alter my code to accomplish this?
For Each g As KeyValuePair(Of [String], List(Of DataRow)) In grouped
For Each row As DataRow In g.Value
If CInt(segment(1)) <= 4 Then
'THIS THROWS AN OUT OF RANGE EXCEPTION
g.Value.Remove(row)
End If
Next
Next
I only want to remove specific rows based on criteria. Can someone post an example? I am on an old browser the "add comment" function does not work
Can you show a code example of how to use a predicate based on row.Item("ID") with the RemoveAll function?
I tried this and am getting an exception
g.Value.RemoveAll(Function(l) l.Item(Con.ID) Is l.Item(Con.ID).ToString)
Use List.RemoveAll. Not only will this make the act of removing all of the items easier than trying to remove items in some form of looping construct, but it will be dramatically more efficient as the List can reorganize all of the items once at the end, rather than moving the items down one index at a time over and over.
I figured it out using a reverse For loop. I did not see an examlpe on how to use the RemoveAll. Please post an example if you have time
For i As Integer = g.Value.Count - 1 To 0 Step -1
Dim row As DataRow = CType(g.Value(i), DataRow)
Dim segment() As String = row.Item(c._ID).ToString.Split("-"c)
If CInt(segment(1)) <= 4 Then
g.Value.Remove(row)
End If
Next i

navigating through records on a database

Simplest way how to loop and display through records using textbox, combo box and datetimepicker.
Below is a code but still cant figure it out
Dim dr As DataRow
Dim ds As Dataset
Dim dt As DataTable
<code to fill the dataset>
dt = ds.Tables(0)
For Each dr In dt.Rows
Console.WriteLine (dr("ColName"))
Next
ds.Dispose()
You need two loops to do this - an outer loop for the number of rows in the table, and an inner loop for the columns in each row.
You have the For Each for the rows already, but you need to know how many columns are in the DataRow, and print out the value in each column. You can get the count of columns from the DataTable.
Dim cols As Integer
cols = dt.Columns.Count - 1
For Each dr in dt.Rows
For i As Integer = 0 To cols
Console.WriteLine(dr(i).ToString())
Next
Next
Notice that I call ToString() on the value returned from each column, and reference the column by it's ordinal. When you access a specific column in the DataRow, it returns an Object, so you'll need to cast that value to the correct data type for use in your program.
The code you posted would have only printed the value for the column that had "ColName" as it's column name for each row. If you didn't have a column named "ColName" then you would see an error.

Get the BindingSource position based on DataTable row

I have a datatable that contains the rows of a database table. This table has a primary key formed by 2 columns.
The components are assigned this way: datatable -> bindingsource -> datagridview. What I want is to search a specific row (based on the primary key) to select it on the grid. I cant use the bindingsource.Find method because you only can use one column.
I have access to the datatable, so I do manually search on the datatable, but how can I get bindingsource row position based on the datatable row? Or there is another way to solve this?
Im using Visual Studio 2005, VB.NET.
I am attempting to add an answer for this 2-year old question. One way to solve this is by appending this code after the UpdateAll method(of SaveItem_Click):
Me.YourDataSet.Tables("YourTable").Rows(YourBindingSource.Position).Item("YourColumn") = "YourNewValue"
Then call another UpdateAll method.
Well, I end up iterating using bindingsource.List and bindingsource.Item. I didnt know but these properties contains the data of the datatable applying the filter and sorting.
Dim value1 As String = "Juan"
Dim value2 As String = "Perez"
For i As Integer = 0 To bsData.Count - 1
Dim row As DataRowView = bsData.Item(i)
If row("Column1") = value1 AndAlso row("Column2") = value2 Then
bsData.Position = i
Return
End If
Next