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
Related
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
Here is the visual basic windows application form I am currently working on.
https://i.snag.gy/EzoXr3.jpg
How can I write code for the find next button like in this video.
https://www.dropbox.com/s/u93h9jn605uhwsu/CPT341Project2Walkthrough.avi?dl=0
If I can get a syntax to store a index variable outside the private sub of findnext button, I can solve the problem. Because everytime I click the findnext button, I have to find the respective instance of that word in the filetext. Or I can apply some code to find it in the substring of remaining text after its first occurrence.
Below is my code:
Public Class Form1
'Enter your name
'Date
'Class - CPT 341 VB.NET NJIT
Private Sub openBtn_Click(sender As Object, e As EventArgs) Handles openBtn.Click
If OpenFileDialog.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
fileText.Text = My.Computer.FileSystem.ReadAllText(OpenFileDialog.FileName)
End If
End Sub
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
'Bring the form to the inital state for a different search
Dim temp As String = fileText.Text
fileText.Text = temp
outputIndex.ForeColor = Color.Black
'MessageBox to show error for empty search textbox
If inputText.Text = "" Then
MessageBox.Show("Enter Text to Search", "CPT 341 Fall 2018 - Project 2")
Else
'Declare variables
Dim txt As String : Dim x As Integer = 0 : Dim output As String
txt = inputText.Text
If fileText.Text.IndexOf(txt) <> -1 Then
Dim idx As Integer = CStr(fileText.Text.IndexOf(txt))
outputIndex.Text = idx
'Find and highlight the first word searched in the RichTextBox
fileText.Find(txt, x, fileText.TextLength, RichTextBoxFinds.None)
fileText.SelectionBackColor = Color.Yellow
'populate the string with ANSI numbers
output = Asc(txt(0))
For x = 1 To (txt.Length - 1)
output = output & " " & Asc(txt(x))
Next x
outputANSI.Text = output
ElseIf fileText.Text = "" Then
MessageBox.Show("Please open a file to search from", "CPT 341 Fall 2018 - Project 2")
Else
outputIndex.Text = txt & " is not found"
'Bring the form to inital state
fileText.Text = temp
'Change the index textbox text color to red
outputIndex.ForeColor = Color.Red
'Empty the ANSI textbox
outputANSI.Text = ""
End If
End If
End Sub
Private Sub btnFind_Click(sender As Object, e As EventArgs) Handles btnFind.Click
Dim txt As String = inputText.Text
Dim Index As Integer = fileText.Text.IndexOf(txt) + txt.Length
'Find and highlight the word searched in the RichTextBox other than first occurrence
fileText.Find(txt, Index, fileText.TextLength, RichTextBoxFinds.None)
fileText.SelectionBackColor = Color.Yellow
Index = fileText.Text.IndexOf(txt, Index) + txt.Length + 1
End Sub
Private Sub btnWords_Click(sender As Object, e As EventArgs) Handles btnWords.Click
wordCount.Text = fileText.Text.Split(" ").Length
End Sub
Private Sub btnChars_Click(sender As Object, e As EventArgs) Handles btnChars.Click
charCount.Text = fileText.Text.Length
End Sub
End Class
Or any other suggestion would be helpful.
I m new to vb.net & I have a problem that whenever user enters an alphabet he/she will receive message that only numbers are allowed. For this code.... Please help me. I shall be very thankful to you.
Public Class Form1
Private Sub DataGridView1_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
If DataGridView1.CurrentCell.ColumnIndex = 0 Then
Dim combo As ComboBox = CType(e.Control, ComboBox)
If (combo IsNot Nothing) Then
RemoveHandler combo.SelectionChangeCommitted, New EventHandler(AddressOf ComboBox_SelectionChangeCommitted)
AddHandler combo.SelectionChangeCommitted, New EventHandler(AddressOf ComboBox_SelectionChangeCommitted)
End If
End If
End Sub
Private Sub ComboBox_SelectionChangeCommitted(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim combo As ComboBox = CType(sender, ComboBox)
If combo.SelectedItem = "Item1" Then
DataGridView1.CurrentRow.Cells(1).Value = "KG"
DataGridView1.CurrentRow.Cells(3).Value = "100"
DataGridView1.CurrentRow.Cells(2).Value = "Raw Material"
ElseIf combo.SelectedItem = "Item2" Then
DataGridView1.CurrentRow.Cells(1).Value = "Liter"
DataGridView1.CurrentRow.Cells(3).Value = "47"
DataGridView1.CurrentRow.Cells(2).Value = "Raw Material"
ElseIf combo.SelectedItem = "Item3" Then
DataGridView1.CurrentRow.Cells(1).Value = "Pound"
DataGridView1.CurrentRow.Cells(3).Value = "54"
DataGridView1.CurrentRow.Cells(2).Value = "Raw Material"
End If
End Sub
Private Sub Mul_Button_Click(sender As Object, e As EventArgs) Handles Mul_Button.Click
Dim s As Int16 = Convert.ToInt16(DataGridView1.CurrentRow.Cells(3).Value)
Dim s1 As Int16 = Convert.ToInt16(DataGridView1.CurrentRow.Cells(4).Value)
DataGridView1.CurrentRow.Cells(5).Value = s * s1
End Sub
Private Sub DataGridView1_CellValidated(sender As Object, e As EventArgs) Handles DataGridView1.CellValidated
Dim s As Int16 = Convert.ToInt16(DataGridView1.CurrentRow.Cells(3).Value)
Dim s1 As Int16 = Convert.ToInt16(DataGridView1.CurrentRow.Cells(4).Value)
DataGridView1.CurrentRow.Cells(5).Value = s * s1
If DataGridView1.RowCount > 0 Then
Dim sum As Integer
For index As Integer = 0 To DataGridView1.RowCount - 1
sum += Convert.ToInt32(DataGridView1.Rows(index).Cells(5).Value)
Next
TextBox1.Text = sum
End If
End Sub
Private Sub Add_Button_Click(sender As Object, e As EventArgs) Handles Add_Button.Click
If DataGridView1.RowCount > 0 Then
Dim sum As Integer
For index As Integer = 0 To DataGridView1.RowCount - 1
sum += Convert.ToInt32(DataGridView1.Rows(index).Cells(5).Value)
Next
TextBox1.Text = sum
End If
End Sub
End Class
Either wrap your code that has Convert.ToInt16() calls in them with Try/Catch blocks, or convert them to the Int16.TryParse() approach instead.
For example, this line:
Dim s As Int16 = Convert.ToInt16(DataGridView1.CurrentRow.Cells(3).Value)
Could become:
Dim s As Int16
Dim strValue As String = DataGridView1.CurrentRow.Cells(3).Value
If Int16.TryParse(strValue, s) Then
' ... do something with "s" in here ...
' ... continue with code...
Else
MessageBox.Show(strValue, "Invalid Value")
End If
I manage to customize the normal list box with an image, change text and background color when item is selected in ownerdrawn, what I want to achieve now is to drawn a custom highlight color on the item when mouse is hover on the listbox item, is that possible or not..., I provided my sample code below on what I come so far..
If e.Index = -1 Then Exit Sub
Dim listBox As ListBox = CType(sender, ListBox)
e.DrawBackground()
Dim isItemSelected As Boolean = ((e.State And DrawItemState.Selected) = DrawItemState.Selected)
If e.Index >= 0 AndAlso e.Index < listBox.Items.Count Then
Dim textSize As SizeF = e.Graphics.MeasureString(listBox.Items(e.Index).ToString(), listBox.Font)
Dim itemImage As Image = My.Resources.FolderHorizontal
'set background and text color
Dim backgroundColorBrush As New SolidBrush(If((isItemSelected), Color.CornflowerBlue, Color.White))
Dim itemTextColorBrush As Color = If((isItemSelected), Color.White, Color.Black)
e.Graphics.FillRectangle(backgroundColorBrush, e.Bounds)
'draw the item image
e.Graphics.SmoothingMode = SmoothingMode.HighQuality
e.Graphics.DrawImage(itemImage, e.Bounds.X + 2, _
e.Bounds.Y + (e.Bounds.Height - textSize.Height) / 2, _
itemImage.Width, itemImage.Height)
'draw the item text
Dim x, y As Single
Dim h As Single = textSize.Height
Dim rect As Rectangle = e.Bounds
rect.X += listBox.ItemHeight
rect.Width -= listBox.ItemHeight
x = rect.X - 3
y = rect.Y + (rect.Height - h) / 2
Dim itemText As String = listBox.Items(e.Index).ToString()
TextRenderer.DrawText(e.Graphics, itemText, e.Font, _
New Rectangle(x, y, ClientRectangle.Width, ClientRectangle.Height), _
itemTextColorBrush, TextFormatFlags.Default)
'clean up
backgroundColorBrush.Dispose()
End If
e.DrawFocusRectangle()
You can use the IndexFromPoint to do something like that:
Dim mouseIndex As Integer = -1
Private Sub ListBox1_MouseMove(sender As Object, e As MouseEventArgs) _
Handles ListBox1.MouseMove
Dim index As Integer = ListBox1.IndexFromPoint(e.Location)
If index <> mouseIndex Then
If mouseIndex > -1 Then
Dim oldIndex As Integer = mouseIndex
mouseIndex = -1
If oldIndex <= ListBox1.Items.Count - 1 Then
ListBox1.Invalidate(ListBox1.GetItemRectangle(oldIndex))
End If
End If
mouseIndex = index
If mouseIndex > -1 Then
ListBox1.Invalidate(ListBox1.GetItemRectangle(mouseIndex))
End If
End If
End Sub
Then in your drawing code:
If mouseIndex > -1 AndAlso mouseIndex = e.Index Then
backgroundColorBrush = New SolidBrush(Color.DarkMagenta)
End If
I will show you how to do this. All experts say its complicated and cannot be done with a listbox... I was able to do that in 5 minutes
the name of the listbox I created is listPOSSIBILITIES
1) create a variable which is global to your form
Dim HOVERTIME As Boolean = True
2) create MouseEnter event
Private Sub listPOSSIBILITIES_MouseEnter(sender As Object, e As system.EventArgs) Handles listPOSSIBILITIES.MouseEnter
HOVERTIME = True
End Sub
3) create MouseLeave event
Private Sub listPOSSIBILITIES_MouseLeave(sender As Object, e As System.EventArgs) Handles listPOSSIBILITIES.MouseLeave
HOVERTIME = False
End Sub
4) create MouseMove event
Private Sub listPOSSIBILITIES_MouseMove(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles listPOSSIBILITIES.MouseMove
Dim mypoint As Point
mypoint = listPOSSIBILITIES.PointToClient(Cursor.Position)
Dim myindex As Integer = listPOSSIBILITIES.IndexFromPoint(mypoint)
If myindex < 0 Then Exit Sub
listPOSSIBILITIES.SelectedIndex = myindex
End Sub
5) create MouseClick event
Private Sub listPOSSIBILITIES_MouseClick(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles listPOSSIBILITIES.MouseClick
HOVERTIME = False
End Sub
6) create SelectedIndexChanged event
Private Sub listPOSSIBILITIES_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles listPOSSIBILITIES.SelectedIndexChanged
If HOVERTIME Then Exit Sub
'put the rest of your code after this above If statement
End Sub
This works because the MouseClick event is triggered before the SelectIndexChanged event
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