ListViewItem.Selected=True being overridden? - vb.net

Hullo, there. First post. Please be gentle.
I am trying to move a selected item up and down a ListView control using the up and down arrows keys.
Here is my code. It is a Windows Forms project, with a form and a ListView control. MultiSelect=False. Sorting=None. View=Details. A single column.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
ListView1.Items.Add("A")
ListView1.Items.Add("B")
ListView1.Items.Add("C")
ListView1.Items.Add("D")
ListView1.Items.Add("E")
End Sub
Private Sub ListView1_KeyDown(sender As Object, e As KeyEventArgs) Handles ListView1.KeyDown
Dim iInsertAt As Integer
If ListView1.SelectedItems.Count = 1 Then
Dim lSelectedItem As ListViewItem = ListView1.SelectedItems(0)
Select Case e.KeyCode
Case Keys.Up
If lSelectedItem.Index > 0 Then
iInsertAt = lSelectedItem.Index - 1
ListView1.Items.Remove(lSelectedItem)
lSelectedItem = ListView1.Items.Insert(iInsertAt, lSelectedItem)
End If
Case Keys.Down
If lSelectedItem.Index < ListView1.Items.Count - 1 Then
iInsertAt = lSelectedItem.Index + 1
ListView1.Items.Remove(lSelectedItem)
lSelectedItem = ListView1.Items.Insert(iInsertAt, lSelectedItem)
End If
End Select
lSelectedItem.Selected = True
End If
End Sub
The code works fine, except that it does not correctly highlight lSelectedItem when it has been moved ^up^. If you run the code, you can select "A" and shift it down the list with the down arrow key. But the result with the up arrow key is not so good.
Would appreciate any guidance!
Thanks.

That's happened because when you remove the item, the selected index still the same so the selection goes to the next item.
For more information
To correct that you can do something like remove and insert two items from the list In order to maintain the order of the selected index.
ex:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
ListView1.Items.Add("A")
ListView1.Items.Add("B")
ListView1.Items.Add("C")
ListView1.Items.Add("D")
ListView1.Items.Add("E")
End Sub
Private Sub ListView1_KeyDown(sender As Object, e As KeyEventArgs) Handles ListView1.KeyDown
Dim iInsertAt As Integer
If ListView1.SelectedItems.Count = 1 Then
Dim lSelectedItem As ListViewItem = ListView1.SelectedItems(0)
Select Case e.KeyCode
Case Keys.Up
If lSelectedItem.Index > 0 Then
iInsertAt = lSelectedItem.Index - 1
Dim item2 = ListView1.Items.Item(iInsertAt)
'remove and Insert two
ListView1.Items.Remove(item2)
ListView1.Items.Insert(iInsertAt + 1, item2)
ListView1.Items.Remove(lSelectedItem)
lSelectedItem = ListView1.Items.Insert(iInsertAt, lSelectedItem)
End If
Case Keys.Down
If lSelectedItem.Index < ListView1.Items.Count - 1 Then
iInsertAt = lSelectedItem.Index + 1
ListView1.Items.Remove(lSelectedItem)
lSelectedItem = ListView1.Items.Insert(iInsertAt, lSelectedItem)
End If
End Select
End If
End Sub

Related

Trying to fix memory issue with dynamic array for bullets in vb.net

The memory usage in my program keeps going up and up even though I'm deleting the bullets. I honestly cant figure out how to fix it any help is appreciated .
Public Class Form1
Dim bulletsArr(-1) As Bullet
Dim intCount As Integer
Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
Select Case e.KeyCode
Case Keys.Space
ReDim Preserve bulletsArr(intCount)
'' Creates new bullet
Dim bullet1 As New Bullet
Controls.Add(bullet1)
'' Sets the intcount in the array to bullet 1 so bulletsArr(0) = bullet1, bulletsArr(1) = bullets1
bulletsArr(intCount) = bullet1
intCount += 1
bulletsTimer.Enabled = True
Case Keys.D, Keys.Right
pictureBoxPlayer.Top += 10
Case Keys.A, Keys.Left
pictureBoxPlayer.Top -= 10D
End Select
End Sub
Private Sub bulletsTimer_Tick(sender As Object, e As EventArgs) Handles bulletsTimer.Tick
For x = 0 To bulletsArr.Length - 1
If pictureBoxCat1.Bounds.IntersectsWith(bulletsArr(x).Bounds) Then
Me.Controls.Remove(bulletsArr(x))
Else
bulletsArr(x).Left += 3
End If
Next
End Sub
End Class
ive tried resetting the array but then freezes the pictureboxes in spot

Highlighting text when searching for it in vb.net

Hi so I've created a search system with a button, textbox and rich text box to search for items displayed in the rich text box (which are imported from a text file) and to highlight them when found. For some reason when I click the search button, it does not highlight the word that is being searched for.
This is the code I used:
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Dim index As Integer = 0
While index < rtxtEdit.Text.LastIndexOf(txtSearch.Text)
rtxtEdit.Find(txtSearch.Text,index ,rtxtEdit.TextLength, RichTextBoxFinds.None)
rtxtEdit.SelectionBackColor = Color.Red
index = rtxtEdit.Text.IndexOf(txtSearch.Text, index) + 1
End While
End Sub
As stated in this post:
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Dim len = searchText.Length
Dim pos = rtb.Find(searchText, 0, RichTextBoxFinds.NoHighlight)
While (pos >= 0)
rtb.Select(pos, len)
rtb.SelectionBackColor = Color.Yellow
if pos + len >= rtb.Text.Length Then
Exit While
End If
pos = rtb.Find(searchText, pos + len, RichTextBoxFinds.NoHighlight)
End While
End Sub
I'd write that this way instead:
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Dim searchFor As String = txtSearch.Text.Trim
If searchFor <> "" Then
Dim index As Integer = 0
Dim startAt As Integer = 0
Do
index = rtxtEdit.Find(searchFor, startAt, RichTextBoxFinds.None)
If index <> -1 Then
rtxtEdit.SelectionBackColor = Color.Red
startAt = index + 1
End If
Loop While index <> -1
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim index As Integer = 0
'Clears the existing formatting
Dim t = rtxtEdit.Text
rtxtEdit.Text = t
'Incremented the loop condition by 1 so that text at the beginning gets selected as well.
While index < rtxtEdit.Text.LastIndexOf(txtSearch.Text) + 1
rtxtEdit.Find(txtSearch.Text, index, rtxtEdit.TextLength, RichTextBoxFinds.None)
rtxtEdit.SelectionBackColor = Color.Red
index = rtxtEdit.Text.IndexOf(txtSearch.Text, index) + 1
End While
End Sub

Datagridview selections with vb.net

Help pls! I want to automatically select all the rows that has the same value in a particular cell of every rows when the user manually select or click on a particular row. am using vb.net. Thanks.
Although the question is not clear enough, you can try:
Private Sub DataGridView1_CellClick(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick
If e.RowIndex <> -1 Then
If DataGridView1.CurrentCell IsNot Nothing AndAlso DataGridView1.CurrentCell.Value IsNot Nothing Then
findOnGridview(DataGridView1, DataGridView1.CurrentCell.Value.ToString(), DataGridView1.CurrentCell.ColumnIndex)
End If
End If
End Sub
Private Sub findOnGridview(g As DataGridView, s As String, c As Integer)
Dim counter As Integer = 0
For i As Integer = 0 To g.Rows.Count - 1
If g.Rows(i).Cells(c).Value = s Then
g.Rows(i).Cells(c).Style.BackColor = Color.Yellow
Else
g.Rows(i).Cells(c).Style.BackColor = Color.White
End If
Next
End Sub

How to move to another column in datagridview using Enter in vb.net

I have search this one, and most of the answer are in C# and I have try to convert it to VB.NET and do a work around but I cannot find the right code.
What I want is when the user press Enter, it will move to the next column, if the column in that row is last, then it will go down to the second row of the first column.
Thank you.
EDIT:
If e.KeyCode = Keys.Enter Then
e.Handled = True
With dvJOBranch
Dim i As Integer = .CurrentCell.ColumnIndex + 1
.CurrentCell = .CurrentRow.Cells(i)
End With
End If
This code is working but for columns that are not editing, if I am editing in a columns, its not working and this is the error: Current cell cannot be set to an invisible cell.
this should do the trick
Private Sub DataGridView1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DataGridView1.KeyDown
If e.KeyCode = Keys.Enter Then
e.SuppressKeyPress = True
Dim iCol = DataGridView1.CurrentCell.ColumnIndex
Dim iRow = DataGridView1.CurrentCell.RowIndex
If iCol = DataGridView1.Columns.Count - 1 Then
If iRow < DataGridView1.Rows.Count - 1 Then
DataGridView1.CurrentCell = DataGridView1(0, iRow + 1)
End If
Else
DataGridView1.CurrentCell = DataGridView1(iCol + 1, iRow)
End If
End If
End Sub
and this will address the "edit" problem mentioned.
Private Sub DataGridView1_CellEndEdit(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
Dim iCol = DataGridView1.CurrentCell.ColumnIndex
Dim iRow = DataGridView1.CurrentCell.RowIndex
If iCol = DataGridView1.Columns.Count - 1 Then
If iRow < DataGridView1.Rows.Count - 1 Then
DataGridView1.CurrentCell = DataGridView1(0, iRow + 1)
End If
Else
If iRow < DataGridView1.Rows.Count - 1 Then
SendKeys.Send("{up}")
End If
DataGridView1.CurrentCell = DataGridView1(iCol + 1, iRow)
End If
End Sub
to be safe.. you should get your "current" column index when your cell changed.. then you can increment from that.. this will also sort out the problem with the "editing"
Public curcol, currow As Integer
Private Sub DataGridView2_CurrentCellChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGridView2.CurrentCellChanged
Try
curcol = DataGridView2.CurrentCell.ColumnIndex
currow = DataGridView2.CurrentCell.RowIndex
Catch ex As Exception
curcol = 0
currow = 0
End Try
End Sub
Private Sub DataGridView2_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DataGridView2.KeyDown
Select Case e.KeyCode
Case Keys.Enter
DataGridView2.ClearSelection()
Try
If curcol = DataGridView1.Columns.Count - 1 Then
If currow < DataGridView2.Rows.Count - 1 Then
DataGridView2.CurrentCell = DataGridView2(0, currow + 1)
End If
Else
DataGridView2.CurrentCell = DataGridView2(curcol + 1, currow)
End If
Catch ex As Exception
Exit Try
End Try
End Select
End Sub
I think ....
Private Sub DataGridView1_EditingControlShowing(sender As System.Object, e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
AddHandler e.Control.KeyDown, AddressOf cell_KeyDown
End Sub
Private Sub cell_KeyDown(sender As Object, e As KeyEventArgs)
If e.KeyCode = Keys.Enter Then
datagridview1.currentrow.cells(datagridview1.currentcelladress.x+1).selected=true
End If
End Sub

How to Check or Uncheck all Items in VB.NET CheckedListBox Control

I need to select and unselect all items in a VB.NET CheckedListBox control, what is the best way to do this?
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
With clbCheckedListBox
.Items.Add("Select/UnSelect All")
.Items.Add("Enero")
.Items.Add("Febrero")
.Items.Add("Marzo")
.Items.Add("Abril")
.Items.Add("Mayo")
.Items.Add("Junio")
.Items.Add("Julio")
.Items.Add("Agosto")
.Items.Add("Septiembre")
.Items.Add("Octubre")
.Items.Add("Noviembre")
.Items.Add("Diciembre")
.SelectedIndex = 0
End With
End Sub
Private Sub clbCheckedListBox_ItemCheck(sender As Object, e As System.Windows.Forms.ItemCheckEventArgs) Handles clbCheckedListBox.ItemCheck
If e.Index = 0 Then
If e.NewValue = CheckState.Checked Then
For idx As Integer = 1 To Me.clbCheckedListBox.Items.Count - 1
Me.clbCheckedListBox.SetItemCheckState(idx, CheckState.Checked)
Next
ElseIf e.NewValue = CheckState.Unchecked Then
For idx As Integer = 1 To Me.clbCheckedListBox.Items.Count - 1
Me.clbCheckedListBox.SetItemCheckState(idx, CheckState.Unchecked)
Next
End If
End If
End Sub
After Hours the above code work fine for me !
Do you mean something like this:
Dim checked As Boolean = True ' Set to True or False, as required.
For i As Integer = 0 To CheckedListBox1.Items.Count - 1
CheckedListBox1.SetItemChecked(i, checked)
Next
Here I'm just looping through all the CheckedListBox Items and setting their checked state.
Ricardo, perhaps this might be what you are looking for:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim items$() = New String() {"Select/UnSelect All", "Enero",
"Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio",
"Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"}
For Each Str As String In items : clbCheckedListBox.Items.Add(Str) : Next
End Sub ' Private Sub frmMain_Load(sender As System.Object, e As System.EventArgs)
Private Sub clbCheckedListBox_ItemCheck(sender As System.Object, e As System.Windows.Forms.ItemCheckEventArgs) Handles clbCheckedListBox.ItemCheck
If e.Index = 0 Then
Dim newCheckedState As CheckState = e.NewValue
For idx As Integer = 1 To clbCheckedListBox.Items.Count - 1
Me.clbCheckedListBox.SetItemCheckState(idx, newCheckedState)
Next
End If
End Sub
To check all CheckedListBox Item:
For i As Integer = 0 To CheckedListBox1.Items.Count - 1
CheckedListBox1.SetItemChecked(i, True)
Next
To uncheck all CheckedListBox Item:
For i As Integer = 0 To CheckedListBox1.Items.Count - 1
CheckedListBox1.SetItemChecked(i, false)
Next
If button.Text = "Select All" Then
For i As Integer = 0 To checklist.Items.Count - 1
checklist.SetItemChecked(i, True)
Next
Button.Text = "Deselect All"
Else
For i As Integer = 0 To checklist.Items.Count - 1
checklist.SetItemChecked(i, False)
Button.Text = "Select All"
Next
End If
I found that clbCheckedListBox.clearSelection() works well for unselecting all.
Added a separate checkbox called "Select All". On checking and unchecking of this checkbox items of a checklistbox can be selected or unselected. So you can call this Kb() function anywhere in your code:
Private Sub ChkSelectAll_Click(sender As Object, e As EventArgs) Handles ChkSelectAll.Click
Kb(ChkSelectAll.CheckState)
End Sub
Private Sub Kb(ByVal Key As Boolean)
For i As Integer = 0 To ChkLstServices.Items.Count - 1
ChkLstServices.SetItemChecked(i, Key)
Next
End Sub
Put this code in the SelectedValueChanged event.
Private Sub clbCheckedListBox_SelectedValueChanged(sender As Object, e As System.EventArgs) Handles ContrListCheckBox.SelectedValueChanged
If clbCheckedListBox.SelectedIndex = 0 Then
If clbCheckedListBox.GetItemChecked(0) = False Then
For idx As Integer = 1 To clbCheckedListBox.Items.Count - 1
Me.clbCheckedListBox.SetItemChecked(idx, False)
Next
Else
For idx As Integer = 1 To ContrListCheckBox.Items.Count - 1
Me.clbCheckedListBox.SetItemChecked(idx, True)
Next
End If
ElseIf clbCheckedListBox.SelectedIndex > 0 Then
If clbCheckedListBox.CheckedItems.Count = clbCheckedListBox.Items.Count - 1 And clbCheckedListBox.GetItemChecked(0) = False Then
clbCheckedListBox.SetItemCheckState(0, CheckState.Checked)
End If
For idx As Integer = 1 To clbCheckedListBox.Items.Count - 1
If clbCheckedListBox.GetItemChecked(idx) = False Then
clbCheckedListBox.SetItemCheckState(0, CheckState.Unchecked)
End If
Next
End If
End Sub
Other solutions are correct but if you want to deselect another checkbox inside the CheckBoxList or empty the CheckBoxList without the Select All checkbox
the top checkbox will remain checked and it is not logical so the above code should solve this problem.
Another option would be to bundle the check/uncheck events - of two buttons, for example - into one handler and use the value of sender to set the check state:
Private Sub clbCheckedListBox(
ByVal sender As Object,
ByVal e As EventArgs) Handles btnAll.Click, btnNone.Click
For i As Integer = 0 To clbApis.Items.Count - 1
clbApis.SetItemChecked(i, sender Is btnAll)
Next i
End Sub