Display related matches from database to TextBox popup when we enter some word in textbox in vb.net - vb.net

i have some problem in Vb.net , i done Google since last 2 days but not getting any related answer of my question , qtn is when user type some text in Text Box so related that text how to display popup just like when we enter some word in Google then Google show all related fields .. guys i m attaching a snapshot please help me ..
i m using vb.net as back end
and MS-Access as front end

Hey guys i got the answer
Step by step (vb.net)
1st declare this as a global
Dim lst As New List(Of String)
Dim rdrOLEDB As OleDbDataReader
Dim MySource As New AutoCompleteStringCollection()
2nd on form load or as per u r logic but make sure it comes only at one time means dont include this code in 3rd step( that is key down)
If ComboBox1.SelectedItem <> "" Then
ComboBox4.Enabled = True
cmdOLEDB.CommandText = "SELECT studentname FROM StudentDetail WHERE std = '" & ComboBox1.SelectedItem & "' "
cmdOLEDB.Connection = cnnOLEDB
rdrOLEDB = cmdOLEDB.ExecuteReader
If rdrOLEDB.Read = True Then
lst.Add(rdrOLEDB.Item(0).ToString)
While rdrOLEDB.Read
lst.Add(rdrOLEDB.Item(0).ToString)
End While
End If
rdrOLEDB.Close()
MySource.AddRange(lst.ToArray)
TextBox2.AutoCompleteCustomSource = MySource
'Auto complete mode set to suggest append so that it will sugesst one
'or more suggested completion strings it has bith ‘Suggest’ and
'‘Append’ functionality
TextBox2.AutoCompleteMode = AutoCompleteMode.SuggestAppend
'Set to Custom source we have filled already
TextBox2.AutoCompleteSource = AutoCompleteSource.CustomSource
Else
MsgBox("please select std.")
End If
3rd step that is text box key down
If e.KeyCode = Keys.Enter Then ' On enter I planned to add it the list
If Not lst.Contains(TextBox2.Text) Then ' If item not present already
' Add to the source directly
TextBox2.AutoCompleteCustomSource.Add(TextBox2.Text)
End If
ElseIf e.KeyCode = Keys.Delete Then 'On delete key, planned to remove entry
' declare a dummy source
Dim coll As AutoCompleteStringCollection = TextBox2.AutoCompleteCustomSource
' remove item from new source
coll.Remove(TextBox2.Text)
' Bind the updates
TextBox2.AutoCompleteCustomSource = coll
' Clear textbox
TextBox2.Clear()
End If ' End of ‘KeyCode’ condition
if its help full then please dont forget to click on point for other peaople search ( parden me for my bad english)

Related

Read CSV to series of existing textbox in Vb.net

I have a code to import csv to auto generated text box which was a part of my previous app. However I had to re do the whole script which involves importing csv to multiple existing textbox.
Below is my old code which worked like a charm but in this code my textbox were getting auto generated based on the numbers of value present in my csv.
Dim T(100) As TextBox
Using ofd As New OpenFileDialog()
If ofd.ShowDialog() = DialogResult.OK Then
TextBox1.Text = (ofd.FileName)
End If
Using MyReader As New Microsoft.VisualBasic.
FileIO.TextFieldParser(TextBox1.Text)
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim numer As Integer
Dim currentRow As String()
numer = 1
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
If (currentField IsNot "") Then
Dim myTB As New TextBox
T(numer) = myTB
myTB.Text = currentField
myTB.Visible = True
myTB.Location = New Point(550, 92 + (numer * 28))
myTB.Name = "ADBox" + numer.ToString
myTB.ReadOnly = True
Me.Controls.Add(myTB)
numer += 1
End If
Next
Catch ex As Microsoft.VisualBasic.
FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
"is not valid and will be skipped.")
End Try
End While
End Using
End Using
But that created a lot of issue in my app hence I had to load the values on an existing textboxes(Multiple) but I am somehow not able to.
Edit1:
*** The code above creates a textbox and adds my csv values to it and what I am looking for is inject csv to existing textbox which I have created and not automatically generated text box.
For Example my code creates text box called ADUser1,2,3,4 and enters all the value but my following code which will create a textfile by fetching the values from the text box is not working because when I declare
My.Computer.FileSystem.WriteAllText(aduser1, ADBox1.Text, True)
it says it doesn't exists because when a form loads it never created such textboxes. This is the challenge I am facing
Any help will be a great value
Thanks
I agree that this is a very awkward design and should be redone, but for the purpose of answering your question...
The reason your code here: My.Computer.FileSystem.WriteAllText(aduser1, ADBox1.Text, True) doesn't find ADBox1 is that it is not created and referenced like an object you drag on to the form. It could be, by the way, but that is more work than dragging and naming 100+ text boxes on your form. Nuts. Creating the textboxes in code is better.
If you "manually" add one textbox to a form, then examine the designer-generated code for the form you will see that it created a textbox for you. You would find something similar to Friend WithEvents ADBox1 As System.Windows.Forms.TextBox. This is the reason you can reference the textbox in your form code. There is no magic here and you are technically doing the same thing in your code, here:
Dim T(100) As TextBox
...
Dim myTB As New TextBox
T(numer) = myTB
You can use the reference T(n) to refer to any of your textboxes. It is not clear where the WriteAllText function is but you may need to be sure Dim T(100) As TextBox is a form global, then change the WriteAllText line like this to get at ADBox1:
My.Computer.FileSystem.WriteAllText(aduser1, T(1).Text, True)

Pop up window with textbox after selecting checkbox

all
I am working on a project with vb.net and MySQL database.
Now for taking information I have added few checkboxes, and in case if user selects a checkbox named other I want a window to appear and it should have a text box and when user enters the text at that box, the details should be stored in db.
As you haven't provided much information I may can't answer exactly your question but check if this can help.
First Add LINQ to SQL (.dbml File) - Let's name it as XYZ and Dataset (.xsd File) - let's name this as XYZ too, to your project and then drag and drop your database table in both the files and save all.
Now going into your form which contains the check box you mentioned.
Add this code to you checkbox click_event.
If checkbox1.checked = True Then
Dim insertValue As String = ""
insertValue = InputBox("Enter text to insert", YourTitle, "")
If inserValue <> "" Then
Dim db as New XYZDataContext
Dim NewRec As New YourTableName With {.ColumnName = insertValue}
db.YourTableName.InsertOnSubmit(NewRec)
db.SubmitChanges()
Msgbox("Value added!")
End If
checkbox1.checked = False
End If
create your window in the designer and give it a name like someWindow. then in your code open the window from the click event of your checkbox. when you close the window don't dispose it. just hide it me.hide so when you window closes you can retrieve the data from your textbox.
Sub Test ()
Dim wd_SomeInfo as new someWindow
wd_SomeInfo.showdialog()
Dim result As String = wd_SomeInfo.txt_sometextbox.text
If result = "" Then cancel....
End Sub

VB.net load controls and content from textfile to textboxes

...Hopefully this question will be readable...
I have 27 textboxes.
The controlname and the text in the textboxes are written to a textfile like this:
System.DateTime.Now.ToString("yyyyMMdd") & "_Names_Config.txt"
Dim objWriter As New System.IO.StreamWriter(configfile, True)
'Textboxes
objwriter.Writeline("tbmax1") 'Control name
objwriter.Writeline("tbmax1.text) 'The text in the textbox
objWriter.WriteLine("tbname1") 'Control name
objWriter.WriteLine(tbname1.Text) 'The text in the textbox
objWriter.WriteLine("tbext1") 'Control name
objWriter.WriteLine(tbext1.Text) 'The text in the textbox
'And so on for all the the controls
This goes on for all the textboxes and controls, so 54 lines in total.
Works great. The textfile looks like this:
Alright, now the issue. There will be a load button that should search the textfile -> find the control matching the form's control -> use the line below and fill that spesific line in the control's textbox -> then find next control and do the same.
Load button: This is #1 attempt;
'Openfiledialog, then:
Using reader As New StreamReader(OpenFileDialog1.FileName.ToString)
Dim currentTextBox As TextBox = Nothing
While reader.Peek > -1
Dim line As String = reader.ReadLine()
If Not String.IsNullOrEmpty(line) Then
Dim tmpTextbox = Controls.Find(line, True) 'Try to find text according to line
If tmpTextbox.Any() Then 'It´s a textbox name
currentTextBox = DirectCast(tmpTextbox(0), TextBox)
Else
'?
End If
End If
End While
End Using
Here comes what I don't understand at all. See before and after picture of what happens to the 27 textboxes after I load the textfile.
What it SHOULD look like:
What it will look like:
"Edit channels" is actually the title of the form itself. I'm speechless. Because I totally don't understand why this happens and the load code, I moved on to another attempt.
#2 attempt:
Using reader As New StreamReader(OpenFileDialog1.FileName)
Dim Line As String = reader.ReadLine()
Dim Current As Integer = 0
Dim TB As TextBox = Nothing
While Not IsNothing(Line) 'It will be Nothing when file is over
'__________________________________________________________________1
If Line.StartsWith("tbext1") Then
'We will increment CurrentChannel, as we changed the section
Current += 1
For onetonine = 1 To 9
tbext1.Text = Line
Next
End If
If Line.StartsWith("tbname1") Then
'We will increment CurrentChannel, as we changed the section
Current += 1
For onetonine = 1 To 9
tbname1.Text = Line
Next
End If
If Line.StartsWith("tbmax1") Then
'We will increment CurrentChannel, as we changed the section
Current += 1
For onetonine = 1 To 9
tbmax1.Text = Line
Next
End If
'__________________________________________________________________2
'Then I guess this would go on for all the 27 textboxes (probably a really bad attempt)
End While
End Using
However, this just goes into break mode.
Your first approach works already if you fill the Else part:
If tmpTextbox.Any() Then
currentTextBox = DirectCast(tmpTextbox(0), TextBox)
ElseIf currentTextBox IsNot Nothing Then
currentTextBox.Text = line
End If
But you should not use it in production code:
Control-names are a very bad key for a database record or file entry:
They can change in future and you won't notice it
They are GUI related and not supposed to be identifiers for properties
is not fail-safe because there could be multiple controls with the same name
don't store key-value pairs on different lines, that makes it difficult, less readable and more error-prone to put them together afterwards
If you want to use one line you need a delimiter that a user never enters, it can be a combination of multiple characters like |::| or something similar. Then you can later use String.Split({"|::|"}, StringSplitOptions.None) to get both tokens back.
However, this is still not a good approach and also not 100% safe. So better approaches were
serialize/deserialize a List(Of String).
If you want to store it in a way that a human can read you should prefer XML.
Here's an example how you can write/read xml easily:
' write all TextBoxes to a file '
Dim allTextBoxes = TextBoxPanel.Controls.OfType(Of TextBox)()
Dim doc As New XDocument(New XElement("Channels"))
For Each txt In allTextBoxes
doc.Root.Add(New XElement(txt.Name, txt.Text.Trim()))
Next
doc.Save(OpenFileDialog1.FileName)
' later read it ... '
Dim xml As XDocument = XDocument.Load(OpenFileDialog1.FileName)
For Each element As XElement In xml.Descendants("Channels").Descendants()
Dim txt = allTextBoxes.FirstOrDefault(function(t) t.Name = element.Name)
If txt IsNot nothing
txt.Text = element.Value
End If
Next

Check DGV row for missing value with an sql bound back end

I am currently working in vb.net windows express 2013 with an sql back end. I am trying to create an if statement that will look at a specific cell and make a decision based on if the cell has nothing in it or not. I think the return for an sql statement is null but im not 100% sure. I have tried lots of codes I dug up on the internet but none of them have worked for me so far. Here is the line:
Dim Row_Index As Integer = DGVStart.CurrentCell.RowIndex
If DGVStart.Rows(Row_Index).Cells(1).Value Is Nothing Then
This code does work, as in the windows express is telling me the line is fine, however, it seems that I am always getting the return of nothing, even if something is in the cell.I think this problem has something to do with the way i am pulling the value. I have a datagridview checkbox column which i manually added in the design form and if i change it to cells(0), which is my manually inserted column, it picks it up every time. I need to know how to tell my program to differentiate between is null and is not null.
UPDATE: I am now running into new issues after changing to searching for dbnull. here is my code.
Private Sub DGVStart_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DGVStart.CellContentClick
'dim start time
Dim start As String = TxtStart.Text
'fail safe so headers cant be clicked
If e.RowIndex = -1 Then
Exit Sub
End If
'dim row index and check, check is for the parts shear columns
Dim Row_Index As Integer = DGVStart.CurrentCell.RowIndex
'Dim check As String = DGVStart.Rows(Row_Index).Cells(2).Value
'if checkbox is clicked
If e.ColumnIndex = 0 Then
'---------------------------------------------Normal parts---------------------------------------------------------------
'If DGVStart.Rows(Row_Index).Cells(1).Value Then
If IsDBNull(DGVStart.Rows(Row_Index).Cells(3).Value) = True Then
Dim Shear As Date = DGVStart.Rows(Row_Index).Cells(5).Value
Dim Machine As Int16 = DGVStart.Rows(Row_Index).Cells(4).Value
Dim ShearNumber As String = DGVStart.Rows(Row_Index).Cells(1).Value
Dim Parts As String = DGVStart.Rows(Row_Index).Cells(3).Value
'Pull Values for sql statement and other operations
Try
'set up for checkbox event to trigger
If e.ColumnIndex = 0 Then
'safety messagebox
Dim result As Integer = MsgBox("Are you sure Shear Number " & ShearNumber & " is being started?", MessageBoxButtons.YesNo)
'if messagebox is no
If result = DialogResult.No Then
Exit Sub
'if messagebox is yes
ElseIf result = DialogResult.Yes Then
'sql update
Using conn1 As New SqlConnection(connstring)
conn1.Open()
Using comm1 As New SqlCommand("UPDATE table1 SET " & start & " = getdate() Where col = value AND col = value", conn1)
With comm1.Parameters
.AddWithValue("#Shear", Shear)
.AddWithValue("#Machine", Machine)
End With
comm1.ExecuteNonQuery()
End Using
conn1.Close()
End Using
End If
End If
Catch ex As Exception
MsgBox(ex.ToString)
MsgBox("Error checking off start date for this machine, please contact the manufacturing enginnering department.")
End Try
Call refresh()
Call refresh2()
'--------------------------------------------------------Parts special--------------------------------------------------
Else
MsgBox("Parts")
End If
End If
End Sub
***Please note my sql statements have been modified to protect the company I am working for but I am sure the sql code works.
NEW PROBLEM: I am receiving a null error message because if i uncomment this line:
If DGVStart.Rows(Row_Index).Cells(1).Value Then
Then I am trying to see if a cell is null but that causes an error. I am trying to use my if statement to either run the normal parts, or special parts of my code.
Thanks,

VB.NET - Combobox goes blank when a button is clicked, databind doesn't update

Please forgive me, it has been some time since I've used VB.Net so this may be easy.
I have a simple login form with a text box, combobox and a button. The combobox is binded to a SQL database and displays the user names from Users table. The idea is that you select a name, type in a password, and you logon to a new form (This part works Great!). If you type a wrong password, the form pops up a message that says "invalid." For some reason at this stage, the combobox goes blank. The drop down now has empty spaces where names once were. Typing in a name with a password here results in object reference errors. I have tried everything to get the combo box to reset and searched the web but nothing works!!!
(I know this is not a secure login, this is just an easy example of binding data to a combo box and checking it against SQL table). Thanks for your help!
enter code here
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles BTN_Logon.Click
Try
Dim STR_User As String = Users_nameComboBox.SelectedValue
Dim STR_Pwd As String = TB_Pwd.Text
STR_User = STR_User.Trim
'MessageBox.Show(STR_User & "|" & STR_Pwd)'Used to verify this stage works
Dim numRecords As Int16 = UsersTableAdapter.FillByLogin(Me.Login_testDataSet.users, STR_User, STR_Pwd)
'MessageBox.Show(numRecords) 'Used to verify this stage works
If (numRecords > 0) Then
Dim DB_User As String = Me.Login_testDataSet.users(0).users_name.Trim
Dim DB_Pwd As String = Me.Login_testDataSet.users(0).users_pwd.Trim
'MessageBox.Show(DB_User & "|" & DB_Pwd)'Used to verify this stage works
If DB_User.Equals(STR_User) And DB_Pwd.Equals(STR_Pwd) Then
'User is authenticated for application
'This section works (removed to cleanup code)
Else
MessageBox.Show("ERROR" & STR_User & "|" & STR_Pwd) 'Shows that this stage works
'Need to figure out why combobox doesn't refill, using restart for now
'Application.Restart()
End If
End If
MessageBox.Show("ERROR" & STR_User & "|" & STR_Pwd) 'Shows that this stage works
'Need to figure out why combobox doesn't refill, using restart for now
'Application.Restart()
Catch ex As Exception
MessageBox.Show(ex.Message)
'Need to figure out why combobox doesn't refill, using restart for now
'Application.Restart()
End Try
End Sub
InitializeComponent
'Users_nameComboBox
Me.Users_nameComboBox.DataBindings.Add(New System.Windows.Forms.Binding("Text",
Me.UsersBindingSource, "users_name", True))
Me.Users_nameComboBox.DataBindings.Add(New System.Windows.Forms.Binding("SelectedValue", Me.UsersBindingSource, "users_name", True))
Me.Users_nameComboBox.DataSource = Me.UsersBindingSource
Me.Users_nameComboBox.DisplayMember = "users_name"
Me.Users_nameComboBox.Name = "Users_nameComboBox"
Me.Users_nameComboBox.ValueMember = "users_name"