prevent go to next row when duplicated value in `datagridview` - vb.net

I have datagrid that user will add values in just one column , and i want to prevent duplicated data in this column, i had mange that by the code bellow,
what I want is to keep the selection (focus) in the same editing cell(x)
if the entered data is duplicated, so I tried to get the current row index and return to it if the data is duplicated but its not working.
row_index = DataGridView1.CurrentRow.Index.ToString()
Dim cell As DataGridViewCell = DataGridView1.Rows(row_index).Cells(1)
DataGridView1.CurrentCell = cell
DataGridView1.BeginEdit(True)
NOTE : User will Add barcode number, so he will use barcode scanner or add it manually and press enter key.
Private Sub DataGridView1_RowValidated(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.RowValidated
If DataGridView1.Rows.Count > 2 Then
Dim i As Integer = 0
Dim row_index As Integer
' loop condition will loop while the row count is less or equal to i
While i <= DataGridView1.Rows.Count - 1
Dim j As Integer = 1
' loop condition will loop while the row count is less or equal to j
While j <= DataGridView1.Rows.Count - 1
Dim str As String = DataGridView1.Rows(i).Cells(1).Value()
Dim str1 As String = DataGridView1.Rows(j).Cells(1).Value()
If Not str1 = "" AndAlso Not str = "" Then
If str1 = str Then
'row_index = DataGridView1.SelectedCells.Item(i).RowIndex.ToString()
row_index = DataGridView1.CurrentRow.Index.ToString()
Dim cell As DataGridViewCell = DataGridView1.Rows(row_index).Cells(1)
DataGridView1.CurrentCell = cell
DataGridView1.BeginEdit(True)
Exit Sub
End If
End If
j += 1
End While
i += 1
End While
End If
End Sub

You can try it also in a for loop. This is how I do it. If what you mean is to stop/retain the selection(focus) or go to in a cell/row whenever it is a duplicate with the current data you have. This should work fine.
enter code here
For i = 0 To Datagridview1.Rows.Count - 1
If Datagridview1.Rows(i).Cells(1).Value = DataYouWillInput Then
DataGridView1.CurrentCell = DataGridView1.Rows(i).Cells(1)
Exit for
End If
Next
enter code here

If your condition returns true with the condition of current data and data you'll be adding. Just exit your loop. Use this.
DataGridView1.CurrentCell = DataGridView1.Rows(i).Cells(1)

Related

Conditional formatting of DataGridView cell data - Change color on negative

I was hoping to be able to use color based conditional formatting in the DefaultCellStyle.Format field for DataGridView cells, in a similar way to how Excel handles this.
For example in Excel, a format string of £#,##0.00;[Red]-£#,##0.00 will display negative values in red.
Is this supported in VB.NET ?
I am aware I can use the .CellFormatting event to conditionally change cell text color but was looking for a less bulky and restrictive way of doing this.
By creating the following CellFormatting addition, I am able to use Excel style conditional colour formatting in the cells format field. Setting the colour for negative/positive/zero values is supported.
Format string is expected to be in the following format (all colours optional) :
[colour]<format for +value> ; [colour]<format for -value> ; [colour]<format for zero value>
..a test DGV column with conditional formatting
c = New DataGridViewColumn
c.Name = "AmountOUT"
c.DataPropertyName = c.Name
c.HeaderText = "AmountOUT"
c.CellTemplate = New DataGridViewTextBoxCell
c.DefaultCellStyle.Format = "[Green]£0.00;[Red]-£0.00;[Blue]zero"
.Columns.Add(c)
..
Private Sub DataGridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
'Split format string to positive / negative / zero components
Dim posnegzero As List(Of String)
posnegzero = e.CellStyle.Format.Split(CChar(";")).ToList
Dim coloursPNZ As New List(Of String)
Dim remainderformatPNZ As String = ""
For Each s As String In posnegzero
If s.Contains("[") And s.Contains("]") Then
'Extract [xxx] contents
coloursPNZ.Add(s.Substring(s.IndexOf("[") + 1, s.IndexOf("]") - s.IndexOf("[") - 1))
'Append rebuilt format excluding [xxx]
remainderformatPNZ &= s.Substring(0, s.IndexOf("[")) & s.Substring(s.IndexOf("]") + 1, s.Length - s.IndexOf("]") - 1) & ";"
Else
coloursPNZ.Add("")
remainderformatPNZ &= s & ";"
End If
Next
'Set format excluding any [xxx] components
e.CellStyle.Format = remainderformatPNZ
'Check for positive value
If Val(e.Value) > 0 And coloursPNZ.Count >= 1 Then
If coloursPNZ(0) <> "" Then
e.CellStyle.ForeColor = Color.FromName(coloursPNZ(0))
End If
End If
'Check for negative value
If Val(e.Value) < 0 And coloursPNZ.Count >= 2 Then
If coloursPNZ(1) <> "" Then
e.CellStyle.ForeColor = Color.FromName(coloursPNZ(1))
End If
End If
'Check for zero value
If Val(e.Value) = 0 And coloursPNZ.Count >= 3 Then
If coloursPNZ(2) <> "" Then
e.CellStyle.ForeColor = Color.FromName(coloursPNZ(2))
End If
End If
End Sub
Dim dgv As DataGridView = Me.DataGridView1
For i As Integer = 0 To dgv.Rows.Count - 1
For ColNo As Integer = 4 To 7 ' number columns
If Not dgv.Rows(i).Cells(ColNo).Value < 0 Then
dgv.Rows(i).Cells(ColNo).Style.BackColor = vbcolor.Red
End If
Next
Next
checking for negative values lookout for strings format and check accordingly
Tryparse will convert the input to an integer if it succeeds - you don't need both the comps and value variables. Here's an example of how it works:
Dim comps As Integer
Dim input As String = "im not an integer"
Dim input2 As String = "2"
'tryparse fails, doesn't get into comps < 0 comparison
If Integer.TryParse(input, comps) Then
If comps < 0 Then
'do something
End If
Else
'I'm not an integer!
End If
'tryparse works, goes into comps < 0 comparison
If Integer.TryParse(input2, comps) Then
If comps < 0 Then
'do something
End If
End If

Visual Basic: How can i display the prime numbers between 1 and the inputted number

Hello everyone so i'm trying to find the prime numbers of any input. I want them to be in a listbox and the input in a text box. I would like to use two arguments but i don't know how to. this is the code i have i need dire help. I am not the best at visual basic i just need some guidance. My code isn't working but display a drop down box when i press display.
Public Class Form1
Private Sub Button3_Click_1(sender As Object, e As EventArgs) Handles Button3.Click
Dim prim As Integer
Dim test As Integer
Dim imPrime As Boolean = False
prim = CInt(txtNum.Text)
test = prim
If prim = 1 Then
imPrime = False
MessageBox.Show("Enter a number greater than one please")
Else
Do While prim >= 2
For i As Integer = 2 To prim
If prim Mod i = 0 Then
imPrime = False
Exit For
Else
imPrime = True
lstPrime.Items.Add(prim)
End If
Next
Loop
End If
If imPrime = True Then
lstPrime.Items.Add(prim)
End If
End Sub
End Class
This is my fastest VBA code to generate prime numbers between two numbers.
The generated prime numbers are put in clipboard. You will need to open
your ms office word and type Ctrl+V to view all the generated prime numbers.
Sub generateprimenumbersbetween()
Dim starting_number As Long
Dim last_number As Long
Dim primenumbers As Variant
Dim a As Long
Dim b As Long
Dim c As Long
starting_number = 1 'input value here
last_number = 1000000 'input value here
primenumbers = ""
For a = starting_number To last_number
c = Round(Sqr(a)) + 1
For b = 2 To c
If a = 1 Or (a Mod b = 0 And c <> b) Then
Exit For
Else
If b = c Then
primenumbers = primenumbers & " " & a
Exit For
End If
End If
Next b
Next a
Dim answer As DataObject
Set answer = New DataObject
answer.SetText primenumbers
answer.PutInClipboard
End Sub
I think the while loop is not working as you intend. You need two loops, the first one counting up to the possible prime, and an inner one counting up to the counter in the outer loop.
You can find examples everywhere... here's one implemented in C#, but since your question was specifically about a listbox, I've translated it to VB.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
calculatePrimes()
End Sub
Private Sub calculatePrimes()
Dim prim As Integer
Dim count As Integer = 0
prim = CInt(Me.TextBox1.Text)
If prim < 3 Then
MsgBox("Please enter a bigger number")
Return
End If
Me.ListBox1.Items.Clear()
For i As Integer = 1 To prim
Dim isPrime As Boolean = True
For j As Integer = 2 To i
If (i Mod j <> 0) Then count = count + 1
Next
If count = (i - 2) Then Me.ListBox1.Items.Add(i)
count = 0
Next
End Sub
End Class
(This assumes you have a textbox for input called TextBox1 and a listbox for display called ListBox1)

Check datatable has row at selected index using loop

Check if datatable has row at selected index using a for loop
i Want to check here if datatable has row at that value of 'i' which comes from loop
Private Sub btnAct_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAct.Click
Gross = 0
Dim i As Integer
Dim dr As DataRow = Nothing
Act1 = dt.Rows(0)("Account")
Act2 = dt.Rows(0)("Account")
'Next
For i = 0 To 100 Step 1
If ( i Want to check here if datatable has row at that value of 'i' which comes from loop) Then
else
If (Act1 = Act2) Then
Else
Act1 = dt.Rows(i - 1)("Account")
For k As Integer = 0 To (i - 1) Step 1
Act2 = Convert.ToString(dt.Rows(k)("Account"))
If (Act1 = Act2) Then
Gross += Convert.ToInt32(dt.Rows(k)("Total_Gross_Amount"))
End If
Next
dr = dt.NewRow()
dr("Account") = "Total"
dr("Total_Gross_Amount") = Gross
Gross = 0
dt.Rows.InsertAt(dr, i)
Act2 = Convert.ToString(dt.Rows(i + 1)("Account"))
End If
Act1 = Convert.ToString(dt.Rows(i + 1)("Account"))
dt(i)("Sno") = i + 1
Next
End If
'Next
End Sub
I have a datatable And I want to check it has row at selected value which comes from a for loop
Simple - LINQ to the rescue:
For i = 0 To 100
' Functionally equivalent to
' dt.Rows.Cast(Of DataRow)().ElementAtOrDefault(i).
Dim rowAtIndex = dt.AsEnumerable().ElementAtOrDefault(i)
If rowAtIndex IsNot Nothing Then
' Do something with the row.
End If
Next
Or a slightly less expressive, but better optimised version:
For i = 0 To 100
Dim rowAtIndex As DataRow = Nothing
If i < dt.Rows.Count Then
rowAtIndex = dt.Rows(i)
' Do something with the row.
Else
' Row at index does not exist.
End If
Next
The big question here is though: does i really need to go beyond dt.Rows.Count - 1 (which is the index of the last row in the DataTable)? If not, I'd rather change the loop to
For i = 0 To dt.Rows.Count - 1

How to search in listview

I am trying to create a Loop that will read through the information on my ListView through the SubItem to find the text that matches the text in my Textbox whenever I hit the search button and Focuses the listbox onto the matched text. Below is what I have but it keeps telling me that the value of string cannot be converted. I am also pretty sure that my numbers wont loop correctly but I am not really sure how to cause them to loop endlessly till end of statement.
Dim T As String
T = Lines.Text
For r As Integer = 0 to -1
For C As Integer = 0 to -1
If List.Items(r).SubItems(C).Text = Lines.Text Then
List.FocusedItem = T
End If
Next
Next
End Sub
I don't understand your code, but I do understand the question. Below is example code to search all rows and columns of a listview. Search is case insensitive and supports a "find next match" scenario. If a match or partial match is found in any column the row is selected. TextBox1 gets the text to find. FindBtn starts a new search.
Private SrchParameter As String = ""
Private NxtStrtRow As Integer = 0
Private Sub FindBtn_Click(sender As Object, e As EventArgs) Handles FindBtn.Click
If Not String.IsNullOrWhiteSpace(TextBox1.Text) Then
SrchParameter = TextBox1.Text
NxtStrtRow = 0
SearchListView()
End If
End Sub
Private Sub ListView1_KeyDown(sender As Object, e As KeyEventArgs) Handles ListView1.KeyDown
If e.KeyCode = Keys.F3 Then
SearchListView()
End If
End Sub
Private Sub SearchListView()
' selects the row containing data matching the text parameter
' sets NxtStrtRow (a form level variable) value for a "find next match" scenario (press F3 key)
If ListView1.Items.Count > 0 Then
If SrchParameter <> "" Then
Dim thisRow As Integer = -1
For x As Integer = NxtStrtRow To ListView1.Items.Count - 1 ' each row
For y As Integer = 0 To ListView1.Columns.Count - 1 ' each column
If InStr(1, ListView1.Items(x).SubItems(y).Text.ToLower, SrchParameter.ToLower) > 0 Then
thisRow = x
NxtStrtRow = x + 1
Exit For
End If
Next
If thisRow > -1 Then Exit For
Next
If thisRow = -1 Then
MsgBox("Not found.")
NxtStrtRow = 0
TextBox1.SelectAll()
TextBox1.Select()
Else
' select the row, ensure its visible and set focus into the listview
ListView1.Items(thisRow).Selected = True
ListView1.Items(thisRow).EnsureVisible()
ListView1.Select()
End If
End If
End If
End Sub
Instead of looping like that through the ListView, try using a For Each instead:
searchstring as String = "test1b"
ListView1.SelectedIndices.Clear()
For Each lvi As ListViewItem In ListView1.Items
For Each lvisub As ListViewItem.ListViewSubItem In lvi.SubItems
If lvisub.Text = searchstring Then
ListView1.SelectedIndices.Add(lvi.Index)
Exit For
End If
Next
Next
ListView1.Focus()
This will select every item which has a text match in a subitem.
Don't put this code in a form load handler, it won't give the focus to the listview and the selected items won't show. Use a Button click handler instead.
This is the easiest way to search in listview and combobox controls in vb net
dim i as integer = cb_name.findstring(tb_name.text) 'findstring will return index
if i = -1 then
msgbox("Not found")
else
msgbox("Item found")
end if

Search DataGridView for Integer Then Select Row

The below code should search DataGridView1 which is on the LeaderAccessTable form for an integer that the user inputs into SendFromID, if the DataGridView1's first column contains what the integer that the user has entered into SendFromID then the entire row should be selected. However it doesn't select any rows at all... Can anyone see why? This code is ran from a separate form.
Dim intcount As Integer
For Each Row As DataGridViewRow In LeadersAccessTable.DataGridView1.Rows
If LeadersAccessTable.DataGridView1.Rows(intcount).Cells(0).Value.ToString = SendFromID.Text Then
LeadersAccessTable.DataGridView1.Rows(intcount).Selected = True
End If
Next
MsgBox("Done.")
In the end this code worked.
Dim v_SelectRow As Integer
For counter = 0 To (LeadersAccessTable.DataGridView1.Rows.Count - 1)
For counter2 = 0 To (LeadersAccessTable.DataGridView1.Columns.Count - 1)
If (LeadersAccessTable.DataGridView1.Rows(counter).Cells(0).Value.ToString.Contains(SendFromID.Text)) Then
LeadersAccessTable.DataGridView1.Rows(counter).Cells(0).Selected = True
v_SelectRow = LeadersAccessTable.DataGridView1.CurrentRow.Index
CurrentPoints.Text = LeadersAccessTable.DataGridView1.Item(8, v_SelectRow).Value
'Do Something
Else
'Do Something
End If
Next
Next