vb.net autocomplete with delimiters - vb.net

I've seen several similar older questions but none of them was properly answered, so I'm raising the topic again. What I need is easy: I have a list of strings composed of one or severals words each (in that case separated by ","). I want a textbox to suggest one or more of those strings when the user is typing, but taking into account not only the first word of the string, but also the others. As a silly example, if my string list is:
string 1: bike, redish
string 2: car, red
string 3: cat, brown
When the user types: "b" strings 1 and 3 should be suggested (bike and brown), when the user types "c" or "ca" strings 2 and 3 should be suggested (car and cat).
So far, I got the autocomplete property working but only for the first word (so if my user types "b" only string 1 will be suggested). This is the code:
Dim newstr As New AutoCompleteStringCollection
While dr.Read 'this is a datareader from which I get my list
newstr.Add(dr.Item(0).ToString)
End While
dr.Close()
mytextbox.AutoCompleteMode = AutoCompleteMode.SuggestAppend
mytextbox.AutoCompleteSource = AutoCompleteSource.CustomSource
mytextbox.AutoCompleteCustomSource = newstr
How can I achieve what I need? I thought it would be already implemented, but it seems not. Any help will be greatly appreciated

I do not think an autocomplete source is what you want for this.
Instead I suggest you use a ComboBox in DropDown mode.
ComboBox3.DropDownStyle = ComboBoxStyle.DropDown
You need to make the list part visible when the control gets focus...
Private Sub ComboBox3_GotFocus(sender As Object, e As EventArgs) Handles ComboBox3.GotFocus
ComboBox3.DroppedDown = True
End Sub
Then rebuild the list contents based on whenever the textbox changes.
Private Sub ComboBox3_KeyUp(sender As Object, e As EventArgs) Handles ComboBox3.KeyUp
Dim Ss = ComboBox3.SelectionStart
Dim Sl = ComboBox3.SelectionLength
.... rebuilt the list items here ...
Dim Ss = ComboBox3.SelectionStart
Dim Sl = ComboBox3.SelectionLength
ComboBox3.DroppedDown = True
End Sub
COMPLETE EXAMPLE
Public Class Form4
Dim employees() As String = New String() {"Hamilton, David", _
"Hensien, Kari", "Hammond, Maria", "Harris, Keith", _
"Henshaw, Jeff D.", "Hanson, Mark", "Harnpadoungsataya, Sariya", _
"Harrington, Mark", "Harris, Keith", "Hartwig, Doris", _
"Harui, Roger", "Hassall, Mark", "Hasselberg, Jonas", _
"Harnpadoungsataya, Sariya", "Henshaw, Jeff D.", "Henshaw, Jeff D.", _
"Hensien, Kari", "Harris, Keith", "Henshaw, Jeff D.", _
"Hensien, Kari", "Hasselberg, Jonas", "Harrington, Mark", _
"Hedlund, Magnus", "Hay, Jeff", "Heidepriem, Brandon D."}
Private Sub ComboBox3_GotFocus(sender As Object, e As EventArgs) Handles ComboBox3.GotFocus
ComboBox3.DroppedDown = True
End Sub
Private Sub ComboBox3_KeyUp(sender As Object, e As KeyEventArgs) Handles ComboBox3.KeyUp
Dim Ss = ComboBox3.SelectionStart ' + 1
ComboBox3.Items.Clear()
Dim SearchText As String = UCase(ComboBox3.Text)
For Each Str As String In employees
Dim UStr As String = UCase(Str)
If InStr(UStr, SearchText) = 1 OrElse InStr(UStr, " " & SearchText) > 0 Then
ComboBox3.Items.Add(Str)
End If
Next
ComboBox3.SelectionStart = Ss
ComboBox3.SelectionLength = 0
ComboBox3.DroppedDown = True
End Sub
End Class
MAKE SURE you set the comboboxstyle to DropDown

Related

Find all instances of a word in a string and display them in textbox (vb.net)

I have a string filled with the contents of a textbox (pretty large).
I want to search through it and display all occurances of this word. In addition I need the searchresult to display some charachters in the string before and after the actual searchterm to get the context for the word.
The code below is part of a code that takes keywords from a listbox one by one using For Each. The code displays the first occurance of a word together with the characters in front and after the word - and stop there. It will also display "no Match for: searched word" if not found.
As stated in the subject of this question - I need it to search the whole string and display all matches for a particular word together with the surrounding characters.
Where = InStr(txtScrape.Text, Search)
If Where <> 0 Then
txtScrape.Focus()
txtScrape.SelectionStart = Where - 10
txtScrape.SelectionLength = Where + 50
Result = txtScrape.SelectedText
AllResults = AllResults + Result
Else
AllResults = AllResults + "No Match for: " & item
End If
I recommend that you can split the string into long sentences by special symbols, such as , : ? .
Split(Char[])
You can refer to the following code.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
RichTextBox1.Text = ""
Dim Index As Integer
Dim longStr() As String
Dim str = TextBox3.Text
longStr = TextBox1.Text.Split(New Char() {CChar(":"), CChar(","), CChar("."), CChar("?"), CChar("!")})
Index = 0
For Each TheStr In longStr
If TheStr.Contains(str) Then
RichTextBox1.AppendText(longStr(Index) & vbCrLf)
End If
Index = Index + 1
Next
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Text = "....."
End Sub
End Class
Result:
Try like this:
Dim ArrStr() As String
Dim Index As Integer
Dim TheStr As String
Dim MatchFound As Boolean
MatchFound = False
ArrStr = Split(txtScrape.text," ")
Index = 1
For Each TheStr In ArrStr
If TheStr = Search Then
Console.WriteLine(Index)
MatchFound = True
End If
Index = Index + 1
Next
Console.WriteLine(MatchFound)
Inside the If statement you will get the index there. And MatchFound is the Boolean value if match found.

Split string into Sub String

I Am Using Vb.net. My idea is when I paste (ctrl+v) for example this character :
AHAKAPATARAE
I Have 6 textboxes.
it would automatically paste them in textboxes one by one in order!
so
txtBox1 will contain : AH
txtBox2 : AK
txtBox3 : AP
txtBox4 : AT
texbox5 : AR
texbox6 : AE
The automation of inserting Licence Keys will ease so much
so that user will not work so hard to cut & paste each two digits!
so any suggestion of doing auto-fill inside textboxes..?
Thanks.
This will allow the paste into the first textbox, as well as move forward correctly if the user types the whole thing manually starting in the first box:
Private Sub txtBox1_TextChanged(sender As Object, e As EventArgs) Handles txtBox6.TextChanged, txtBox5.TextChanged, txtBox4.TextChanged, txtBox3.TextChanged, txtBox2.TextChanged, txtBox1.TextChanged
Dim TB As TextBox = DirectCast(sender, TextBox)
Dim value As String = TB.Text
If value.Length > 2 Then
TB.Text = value.Substring(0, 2)
Dim TBs() As TextBox = {txtBox1, txtBox2, txtBox3, txtBox4, txtBox5, txtBox6}
Dim index As Integer = Array.IndexOf(TBs, TB)
If index > -1 AndAlso index < (TBs.Length - 1) Then
index = index + 1
TBs(index).Text = value.Substring(2)
TBs(index).Focus()
TBs(index).SelectionStart = TBs(index).TextLength
End If
End If
End Sub
There are definitely many more ways this could be accomplished...
Handle the key down event on textbox 1
Private Sub txtBox1_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles txtBox1.KeyDown
If e.Modifiers = Keys.Control AndAlso e.KeyCode = Keys.V Then
' Get Clipboard Text
Dim cpText as String = My.Computer.Clipboard.GetText()
' Assign
txtBox1.Text = cpText.Substring(0, 2)
txtBox2.Text = cpText.Substring(2, 2)
txtBox3.Text = cpText.Substring(4, 2)
txtBox4.Text = cpText.Substring(6, 2)
txtBox5.Text = cpText.Substring(8, 2)
txtBox6.Text = cpText.Substring(10, 2)
'the event has been handled manually
e.Handled = True
End If
End Sub
Another option is to have one masked textbox event. Might be easier

iterating through a dataset and apply values from 5 of 7 columns to textboxs in an active report

I want to iterate through a dataSet and apply each value to a textbox in an active report. i dont know if these text boxes need to be a the Group/Header area or what. i know that my code below is only retrieving the first row. how can I iterate through all rows and apply the data to text boxes that active reports manages to get multiple rows in the group section
Private Sub rptUserCellPhoneSwap_ReportStart(sender As Object, e As System.EventArgs) Handles Me.ReportStart
Me.PageSettings.Orientation = GrapeCity.ActiveReports.Document.Section.PageOrientation.Landscape
DateTxt.Text = Now.ToShortDateString & " " & Now.ToShortTimeString
Dim DataSet = GrabInformation(FirstName, LastName)
UserTxt.Text = LastName + ", " + FirstName
'For Each dr As DataRow In DataSet.Tables(0).Rows
' OldIMEITxt.Text = DataSet.Tables(0).Rows(dr("OldIMEI")).ToString
' NewIMEITxt.Text = DataSet.Tables(0).Rows(dr("NewIMEI")).ToString
' ReasonTxt.Text = DataSet.Tables(0).Rows(dr("SwapReason")).ToString
' DateRepTxt.Text = DataSet.Tables(0).Rows(dr("DateSwapped")).ToString
' ValueTxt.Text = DataSet.Tables(0).Rows(dr("EstimatedAccumulatedValue")).ToString
'Next
If Not IsNothing(DataSet) Then
If DataSet.Tables(0).Rows.Count > 0 Then
OldIMEITxt.Text = DataSet.Tables(0).Rows(0)("OldIMEI")
NewIMEITxt.Text = DataSet.Tables(0).Rows(0)("NewIMEI")
ReasonTxt.Text = DataSet.Tables(0).Rows(0)("SwapReason")
DateRepTxt.Text = DataSet.Tables(0).Rows(0)("DateSwapped")
ValueTxt.Text = DataSet.Tables(0).Rows(0)("EstimateAccumulatedValue")
End If
End If
End Sub
ActiveReports can read data from your DataSet without additional loops in code.
if you return the data table to DataSource property of report object, then it is enough to set DataField property of TextBox controls and GroupHeader section correctly to show data in report. the rendering engine will go through all data rows automatically:
Private Sub SectionReport1_ReportStart(sender As Object, e As EventArgs) Handles MyBase.ReportStart
' bind TextBox controls to fields in table
Me.txtF1.DataField = "F1"
Me.txtF2.DataField = "F2"
' set the grouping field
Me.GroupHeader1.DataField = "F2"
' set the report data source
Me.DataSource = GetSampleData().Tables(0)
End Sub
Private Function GetSampleData() As DataSet
Dim ds = New DataSet()
Dim dt = ds.Tables.Add("TestData")
dt.Columns.Add("F1")
dt.Columns.Add("F2")
dt.Rows.Add("1", "0")
dt.Rows.Add("2", "0")
dt.Rows.Add("1", "1")
dt.Rows.Add("2", "1")
Return ds
End Function
if you prefer to read data row by row in "semi-automatic mode", then FetchData event handler can help here:
Dim i As Integer
Dim dt As DataTable = Nothing
Private Sub SectionReport2_ReportStart(sender As Object, e As EventArgs) Handles MyBase.ReportStart
i = 0
' bind TextBox controls to fields in table
Me.txtF1.DataField = "F1"
Me.txtF2.DataField = "F2"
' set the grouping field
Me.GroupHeader1.DataField = "F2"
dt = GetSampleData().Tables(0)
End Sub
Private Sub SectionReport2_DataInitialize(sender As Object, e As EventArgs) Handles MyBase.DataInitialize
Me.Fields.Add("F1")
Me.Fields.Add("F2")
End Sub
Private Sub SectionReport2_FetchData(sender As Object, eArgs As FetchEventArgs) Handles MyBase.FetchData
If dt.Rows.Count > i Then
Me.Fields("F1").Value = dt.Rows(i)(0)
Me.Fields("F2").Value = dt.Rows(i)(1)
eArgs.EOF = False
Else
eArgs.EOF = True
End If
i = i + 1
End Sub
Private Function GetSampleData() As DataSet
Dim ds = New DataSet()
Dim _dt = ds.Tables.Add("TestData")
_dt.Columns.Add("F1")
_dt.Columns.Add("F2")
_dt.Rows.Add("1", "0")
_dt.Rows.Add("2", "0")
_dt.Rows.Add("3", "1")
_dt.Rows.Add("4", "1")
Return ds
End Function
also, i would recommend to look at the sample with run time data binding in the ActiveReports installation package.
here is a link to the sample description on the official site:
Unbound Data
This is how you would loop through to get all rows, but in this example the only data that will be left in the textboxes will be the last row.
if you want to concatenate each rows information in the specified text box then you should have the information like this.
OldIMEITxt.Text = OldIMEITxt.Text & dr("OldIMEI")
Loop Code
For each dr as Datarow in DataSet.Tables(0).Rows
OldIMEITxt.Text = dr("OldIMEI")
NewIMEITxt.Text = dr("NewIMEI")
ReasonTxt.Text = dr("SwapReason")
DateRepTxt.Text = dr("DateSwapped")
ValueTxt.Text = dr("EstimateAccumulatedValue")
Next

Array copy will not work in a if statement or by button click sub

I am trying to make a small log ( string array of 10 ) of time stamps that on a event will move the newest event towards the first string in the array.
Here is a few attempts that I have tried. The only time the array will change is when it is in a timer.
What Iam looking to do is
on a bit change to copy arrayA(1) to array(0). witch will move the string from (1) to (0),(2) to (1),(3) to (2) and the rest of the array. So when the event happens it cascades the strings to make a list of last events (0) would be the 10th event that happened and the (9) would be the first or latest event
Attempt 1
Private Sub RcvTmr_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RcvTmr.Tick
dim SrvUpTimeStgArray(9) as string
If BtnBit = False And OneShot(5) = True Then
OneShot(5) = False
SrvUpTimeStgArray(9) = LAtimeSvrUp.TimeString
For I = 0 To 8
SrvUpTimeStgArray(I) = SrvUpTimeStgArray(I + 1)
Next
LAtimeSvrUp.StopTimer()
End If
ListBox1.DataSource = SrvUpTimeStgArray
End Sub
Then this code to
Private Sub RcvTmr_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RcvTmr.Tick
Dim StringArrayA(9) as string : Dim StringArrayB(9) as string
If OneShot(10) = False Then
OneShot(10) = True
StringArrayA(3) = "testst 33333"
StringArrayA(2) = "testst 22222"
StringArrayA(1) = "testst 11111"
StringArrayA(0) = "testst 00000"
End If
StringArrayA(0) = StringArrayA(1)
If Btn1TestBit Then
counter1 = counter1 + 1
BtnTest3.Text = "worked"
'Call ArrayCopy()
Btn1TestBit = False
StringArrayA(0) = StringArrayA(1)
' The below was alternated with the above line ans also did not work
' Array.Copy(StringArrayA, 1, StringArrayB, 0, 4)
End If
ListBox1.DataSource = StringArrayA
ListBox2.DataSource = StringArrayB
Lacount3.Text = counter1
End Sub
I am missing something so thanks..
Update but It has duplicate strings to the array
This is using the AddLog Sub
If ClientConnBit = False And OneShot(5) = True Then
OneShot(5) = False
AddLog(SrvUpTimeStgArray, "Stopped # " & DateTime.Now.ToString() & "* Up Time " & LAtimeSvrUp.TimeString)
LAtimeSvrUp.StopTimer()
For Each entry As String In SrvUpTimeStgArray
If Not String.IsNullOrEmpty(entry) Then
LBSvrUptimeLog.Items.Add(entry)
End If
Next
'LBSvrUptimeLog.DataSource = SrvUpTimeStgArray
My.Settings.UpTimeString.AddRange(SrvUpTimeStgArray)
My.Settings.Save()
End If
You need to copy the values backward, if you do it forward you'll end up copying the same value everywhere. I suggest you load how to use break point and watch.
This is how it would look like
Sub AddLog(ByVal logAsArray() As String, ByVal newEntry As String)
For index As Integer = logAsArray.Length - 1 To 1 Step -1
logAsArray(index) = logAsArray(index - 1)
Next
logAsArray(0) = newEntry
End Sub
You can also use list instead
Sub AddLog(ByVal logAsList As List(Of String), ByVal newEntry As String)
If logAsList.Count = logAsList.Capacity Then
logAsList.RemoveAt(logAsList.Capacity - 1)
End If
logAsList.Insert(0, newEntry)
End Sub
Here's an example on how to use these functions.
Sub Main()
Dim logAsArray(2) As String
AddLog(logAsArray, "a")
AddLog(logAsArray, "b")
AddLog(logAsArray, "c")
AddLog(logAsArray, DateTime.Now.ToString())
For Each entry As String In logAsArray
Console.WriteLine(entry)
Next
Dim logAsList As New List(Of String)(3)
AddLog(logAsList, "a")
AddLog(logAsList, "b")
AddLog(logAsList, "c")
AddLog(logAsList, DateTime.Now.ToString())
For Each entry As String In logAsList
Console.WriteLine(entry)
Next
Console.ReadLine()
End Sub

add or remove item from DataGrid - vb.net compact framework

I am working on a project that allow users to get order in restaurant with handheld which is windows mobile device. I used datagrid to show existing order and wanted to add item by clicking on a button, or remove item by selecting from datagrid to change the order. Thus, could you please guys help me to figure out what is the best way to working on existing database items. Thanks in advance.
so far my code is,
Getting existing order from database
Public Shared Function MenuItems(ByVal groupNo As Integer) As List(Of Menus)
Dim cmd As New SqlCommand("", Ayar.baglanti)
Dim menuItem As New List(Of Menus)
Try
cmd.CommandText = "SELECT ToppingAutoID, BasePrice, ToppingName, PrinterName, Special, Normal, Irregular," & _
" NavigationID, ModifiersCharge, taxRate, JustNavigate, Terminator, ItemQuantity, ExtraCharge, TripleCharge, " & _
" HalfCharge, OneThirdCharge, OneForthCharge, NoDiscountItem FROM MenuToppings WHERE GroupID = #groupID"
cmd.Parameters.AddWithValue("#groupID", groupNo)
Dim data As New DataSet
data.Load(cmd.ExecuteReader, LoadOption.OverwriteChanges, "menuitem")
Dim dt As DataTable = data.Tables("menuitem")
''
For Each r As DataRow In dt.Rows
Dim item As New Menus
item.Toppingautoid = r("ToppingAutoID")
item.Baseprice = r("BasePrice")
item.Toppingname = r("ToppingName")
item.Itemquantity = r("ItemQuantity")
menuItem.Add(item)
Next
Catch ex As Exception
log.log("MenuItem()fonksiyonunda hata oluştu.", ex.Message)
End Try
MenuItems = menuItem
End Function
Listing existing order on datagrid
Public Function siparisGoster()
Dim isModifed As Boolean = False
Dim skl As New DataGridTableStyle
Dim kolon1, kolon2, kolon3 As New DataGridTextBoxColumn
kolon1.MappingName = "Itemno"
kolon1.HeaderText = "MADAKAFA"
kolon1.Width = -1
kolon2.MappingName = "Itemdesc"
kolon2.Width = 300
kolon3.MappingName = "Itemamount"
kolon3.Width = 10
skl.GridColumnStyles.Add(kolon1)
skl.GridColumnStyles.Add(kolon2)
skl.GridColumnStyles.Add(kolon3)
If isModifed = False Then
Dim ord As Order = Order.GetTableOrder(tableNo)
Dim bs As New BindingSource
bs.DataSource = ord.GetOrderItems
skl.MappingName = bs.GetListName(Nothing)
DataGridItems.BackColor = Color.White
DataGridItems.ColumnHeadersVisible = False
DataGridItems.RowHeadersVisible = False
DataGridItems.TableStyles.Clear()
DataGridItems.TableStyles.Add(skl)
DataGridItems.DataSource = bs
End If
End Function
Paul Yao describes both, a manual and automatic, in-place editing in his book Programming the Compact Framework (VB.NET and C# editions available). You may register at http://www.paulyao.com/cfbook/code to get the code of chapter 8.
excerpt:
Private Sub cmdEdit_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs _
) _
Handles cmdEdit.Click
With dgrdProjects.CurrentCell
' Check the DataSource's column's name
' If it is "ctTasks", do not update.
If dgrdProjects.TableStyles("Projects"). _
GridColumnStyles(.ColumnNumber). _
MappingName = "ctTasks" Then
MessageBox.Show( _
"Count of tasks only changes as the " & _
"result of adding / removing a task.")
Exit Sub
End If
' Position textEdit for in-place editing.
textEdit.Bounds = dgrdProjects.GetCellBounds _
(.RowNumber, .ColumnNumber)
' Load the CurrentCell's value into textEdit.
textEdit.Text = dgrdProjects.Item _
(.RowNumber, .ColumnNumber)
' Highlight the text.
textEdit.SelectAll()
' Show textEdit and set the focus to it.
textEdit.Visible = True
textEdit.Focus()
End With
' Set Form GUI state to "Editing".
Me.SetEditingState(True)
End Sub
...
Private Sub cmdUpdate_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs _
) _
Handles cmdUpdate.Click
' Move the contents of textEdit
' into the CurrentCell
With dgrdProjects
.Item(.CurrentCell.RowNumber, _
.CurrentCell.ColumnNumber) = textEdit.Text
End With
' Set Form GUI state to "Not Editing".
Me.SetEditingState(False)
End Sub
The book is well worth to buy it. It is one of my favorite CF starter.