How to make a validation from a checkbox and radiobutton - vb.net

I'm trying to make a validation where after I click in a item from the ComboBoxwithout check any of the RadioButton it will shows de user a message. This is the piece the code that I am using to get the info from an item and fill it on DataGridView.
Private Sub cbExtensão_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbExtensão.SelectedIndexChanged
If cbExtensão.Visible <> cbExtensão.V(rbPorData.Checked & rbPorExtensão.Checked & rbPorNome.Checked) Then
If rbPorData.Checked Then
DataGridView2.DataSource = FillDataGridViewData(cbExtensão.Text)
ElseIf rbPorExtensão.Checked Then
DataGridView2.DataSource = FillDataGridViewExtensao(cbExtensão.Text)
ElseIf rbPorNome.Checked Then
DataGridView2.DataSource = FillDataGridViewName(cbExtensão.Text)
End If
Else
MsgBox("Please, check an option to search")
End If
End Sub
What I am trying to do is making something with this line If cbExtensão.Visible <> cbExtensão.V(rbPorData.Checked & rbPorExtensão.Checked & rbPorNome.Checked) Then but I've tried a lot of things and I can«t get anything from there. Basically I want it to displays a message if user doens't select any RadioButton after click on an item from CheckBox

this is how I have done it for my code.
Private Sub UserMsgBox(ByVal sMsg As String)
Dim sb As New StringBuilder()
Dim oFormObject As System.Web.UI.Control
sMsg = sMsg.Replace("'", "\'")
sMsg = sMsg.Replace(Chr(34), "\" & Chr(34))
sMsg = sMsg.Replace(vbCrLf, "\n")
sMsg += "<script language=javascript "
sMsg += "type=text/" + "javascript" + ">"
smsg += "alert ('" + "Please click on a code type" + "')"
sMsg += "</" + "script" + ">"
sb = New StringBuilder()
sb.Append(sMsg)
Page.RegisterclientScriptBlock("clientScript", sMsg)
For Each oFormObject In Me.Controls
If TypeOf oFormObject Is HtmlForm Then
Exit For
End If
Next
' Add the javascript after the form object so that the
' message doesn't appear on a blank screen.
oFormObject.Controls.AddAt(oFormObject.Controls.Count, New LiteralControl(sb.ToString()))
end sub

As Plutonix mentionned in the comments, you can just remove the first if statement...
Private Sub cbExtensão_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbExtensão.SelectedIndexChanged
If rbPorData.Checked Then
DataGridView2.DataSource = FillDataGridViewData(cbExtensão.Text)
ElseIf rbPorExtensão.Checked Then
DataGridView2.DataSource = FillDataGridViewExtensao(cbExtensão.Text)
ElseIf rbPorNome.Checked Then
DataGridView2.DataSource = FillDataGridViewName(cbExtensão.Text)
Else
MsgBox("Please, check an option to search")
End If
End Sub
So if no box is selected, it will fall down to the Else statement.

Related

How to split a procedure in few logic parts?

Hi, I'm creating a downloader by halving it in steps so that each part works logically.
The code is divided into:
public class Form1
Public Shared link As String 'I'm sharing data with another form
I insert a url to download in the textchanged event of textbox:
If (My.Settings.Cartellasalvataggio = "") Then
Label2.Text = "Download folder is missing"
' MsgBox("manca destinazione")
Else
If Clipboard.GetText.Contains("youtube") = False Then
Label2.Text = "not a valid youtube link"
Else
If TextBox1.Text = Clipboard.GetText Then
Label2.Text = "you already use it"
Else
TextBox1.Text = Clipboard.GetText
WebBrowser1.Navigate("https://www.320youtube.com/v8/watch?v=" +
_TextBox1.Text.Replace("https://www.youtube.com/watch?v=", ""))
End If
End If
End If
Then, in the document completed event I extract the download link:
Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
Dim collection As HtmlElementCollection = WebBrowser1.Document.All
Dim a As String
For Each element As HtmlElement In collection
If element.TagName = "A" Then
a = element.GetAttribute("HREF")
If a.Length > 70 Then
a.ToString.Replace(" - YouTube", "")
link = a
If link IsNot Nothing Then
Title()
End If
End If
End If
Next
End Sub
If the link variable is not empty then I activate the sub title:
Private Sub Title()
Dim wctitolo As New WebClient()
wctitolo.Encoding = Encoding.UTF8
Dim source As String = wctitolo.DownloadString(TextBox1.Text.Replace(" - YouTube", ""))
Dim title As String = Regex.Match(source, "\<title\b[^>]*\>\s*(?<Title>[\s\S]*?)\</title\>", RegexOptions.IgnoreCase).Groups("Title").Value
Dim a As String = title.Replace(" - YouTube", "")
Dim webdecode As String = WebUtility.HtmlDecode(a)
My.Settings.Titolo = String.Join("-", webdecode.Split(IO.Path.GetInvalidFileNameChars))
Label2.Text = "Getting title..- Step 3/4"
Label1.Text = My.Settings.Titolo
RichTextBox1.AppendText(vbLf + My.Settings.Titolo + Environment.NewLine)
formcs.BetterListBox1.Items.Add(My.Settings.Titolo)
My.Settings.Save()
If Fileexist() Then
Else
If My.Settings.Titolo IsNot Nothing Then
Download()
End If
End If
and sub FileExists () which returns true if the file exists and false if it does not exist. If it does not exist then, as dictated in private sub Title (), I activate the private sub Download ().
Public Function Fileexist() As Boolean
Label3.Text = Label3.Text + "Fileesiste+ "
Dim result As Boolean
Dim cartella = My.Settings.Cartellasalvataggio
Dim filedidestinazione = Directory.GetFiles(cartella,
My.Settings.Titolo + ".mp3",
SearchOption.AllDirectories).FirstOrDefault()
If filedidestinazione IsNot Nothing Then
Dim answer As String
answer = CType(MsgBox("File exist in" + vbLf + My.Settings.Cartellasalvataggio + "\" + My.Settings.Titolo + ".mp3" + vbLf + "Would you like to open the folder?", vbYesNo), String)
If CType(answer, Global.Microsoft.VisualBasic.MsgBoxResult) = vbYes Then
Process.Start("explorer.exe", "/select," & filedidestinazione)
result = True
Else
result = False
answer = CType(vbNo, String)
Label2.Text = "File exist"
End If
End If
Return result
End Function
and at the end, the Download sub:
Public WithEvents mclient As New WebClient
Private Sub mClient_DownloadProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs) Handles mclient.DownloadProgressChanged
Try
Label4.Text = (Val(e.BytesReceived) / 1048576).ToString("0.00") & "MB Scaricati"
Label2.Text = "Download di " + My.Settings.Titolo + " in corso.."
Catch ex As Exception
End Try
End Sub
Private Sub Download()
Label3.Text = Label3.Text + "Download+ "
Dim filepath As String = (My.Settings.Cartellasalvataggio + "\" + Label1.Text + ".mp3")
mclient.Encoding = Encoding.UTF8
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
mclient.Headers.Add(HttpRequestHeader.UserAgent, "")
mclient.DownloadFileAsync(New Uri(link), filepath)
End Sub
I thought everything was fine, but at runtime I get an error for stackoverflow ..
The "Settings.Designer.vb" tab opens with the error
System.StackOverflowException in
<Global.System.Configuration.UserScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("")> _
Public Property Titolo() As String
Get
Return CType(Me("Titolo"),String)
End Get
Set
Me("Titolo") = value
End Set
End Property
is there an easy way I can concatenate these pieces of code in such a way that they work in a logical step by step without modifying to much the code?
Thank you

How to use few subs in order to split the code procedure

I'm creating a downloader by halving it in steps so that each part works logically.
The code is divided into:
public class Form1
Public Shared link As String 'I'm sharing data with another form
I insert a url to download in the textchanged event of textbox:
If (My.Settings.Cartellasalvataggio = "") Then
Label2.Text = "Download folder is missing"
' MsgBox("manca destinazione")
Else
If Clipboard.GetText.Contains("youtube") = False Then
Label2.Text = "not a valid youtube link"
Else
If TextBox1.Text = Clipboard.GetText Then
Label2.Text = "you already use it"
Else
TextBox1.Text = Clipboard.GetText
WebBrowser1.Navigate("https://www.320youtube.com/v8/watch?v=" +
_TextBox1.Text.Replace("https://www.youtube.com/watch?v=", ""))
End If
End If
End If
Then, in the document completed event I extract the download link:
Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
label3.text=label3.text+"link download"
Dim collection As HtmlElementCollection = WebBrowser1.Document.All
Dim a As String
For Each element As HtmlElement In collection
If element.TagName = "A" Then
a = element.GetAttribute("HREF")
If a.Length > 70 Then
a.ToString.Replace(" - YouTube", "")
link = a
If link IsNot Nothing Then
Title()
End If
End If
End If
Next
End Sub
If the link variable is not empty then I activate the sub title:
Private Sub Title()
label3.text=label3.text+"title+ "
Dim wctitolo As New WebClient()
wctitolo.Encoding = Encoding.UTF8
Dim source As String = wctitolo.DownloadString(TextBox1.Text.Replace(" - YouTube", ""))
Dim title As String = Regex.Match(source, "\<title\b[^>]*\>\s*(?<Title>[\s\S]*?)\</title\>", RegexOptions.IgnoreCase).Groups("Title").Value
Dim a As String = title.Replace(" - YouTube", "")
Dim webdecode As String = WebUtility.HtmlDecode(a)
My.Settings.Titolo = String.Join("-", webdecode.Split(IO.Path.GetInvalidFileNameChars))
Label2.Text = "Getting title..- Step 3/4"
Label1.Text = My.Settings.Titolo
RichTextBox1.AppendText(vbLf + My.Settings.Titolo + Environment.NewLine)
formcs.BetterListBox1.Items.Add(My.Settings.Titolo)
My.Settings.Save()
If Fileexist() Then
Else
If My.Settings.Titolo IsNot Nothing Then
Download()
End If
End If
and sub FileExists () which returns true if the file exists and false if it does not exist. If it does not exist then, as dictated in private sub Title (), I activate the private sub Download ().
Public Function Fileexist() As Boolean
Label3.Text = Label3.Text + "Checking if file exist+ "
Dim result As Boolean
Dim cartella = My.Settings.Cartellasalvataggio
Dim filedidestinazione = Directory.GetFiles(cartella,
My.Settings.Titolo + ".mp3",
SearchOption.AllDirectories).FirstOrDefault()
If filedidestinazione IsNot Nothing Then
Dim answer As String
answer = CType(MsgBox("File exist in" + vbLf + My.Settings.Cartellasalvataggio + "\" + My.Settings.Titolo + ".mp3" + vbLf + "Would you like to open the folder?", vbYesNo), String)
If CType(answer, Global.Microsoft.VisualBasic.MsgBoxResult) = vbYes Then
Process.Start("explorer.exe", "/select," & filedidestinazione)
result = True
Else
result = False
answer = CType(vbNo, String)
Label2.Text = "File exist"
End If
End If
Return result
End Function
and at the end, the Download sub:
Public WithEvents mclient As New WebClient
Private Sub mClient_DownloadProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs) Handles mclient.DownloadProgressChanged
Try
Label4.Text = (Val(e.BytesReceived) / 1048576).ToString("0.00") & "MB Scaricati"
Label2.Text = "Download di " + My.Settings.Titolo + " in corso.."
Catch ex As Exception
End Try
End Sub
Private Sub Download()
Label3.Text = Label3.Text + "Download+ "
Dim filepath As String = (My.Settings.Cartellasalvataggio + "\" + Label1.Text + ".mp3")
mclient.Encoding = Encoding.UTF8
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
mclient.Headers.Add(HttpRequestHeader.UserAgent, "")
mclient.DownloadFileAsync(New Uri(link), filepath)
End Sub
I thought It was ok but, Look at this gif Gif example
is there an easy way I can concatenate these pieces of code in such a way that they work in a logical step by step without modifying to much the code?
Thank you
Private Sub Title()
label3.text=label3.text & "title+ "
Public Function Fileexist() As Boolean
Label3.Text = Label3.Text & "Checking if file exist+ "
Private Sub Download()
Label3.Text = Label3.Text & "Download+ "
The label is updating one after the other; it is just happening so fast that you can't see it. To prove it to yourself, put a breakpoint somewhere after the label code in each method and you will see the label text building. BTW, the ampersand is the usual vb concatenation symbol. Any + sign inside a string is not considered a concatenation character. "title+" for example.
I think you will find that your code is more readable if you can start using interpolated strings.

vb.net change combobox options depending on selected item in 2 previous comboboxes

I am creating a program which someone can input a search into a textbox and then narrow down the results using a series of comboboxes (or just use the comboboxes to search through everything).
The program looks like this: form 1
I have made the options in the 2nd combobox change using the following code:
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim type As String = ComboBox1.SelectedItem
Dim make As String = ComboBox2.SelectedItem
Dim model As String = ComboBox3.SelectedItem
Dim version As String = TextBox2.Text
Dim memory As String = TextBox3.Text
Dim problem As String = TextBox4.Text
Dim casenumber As Integer = Int(Rnd() * 9999) + 1000
If type = "Phone" Then
ComboBox2.Items.Clear()
Dim file As New System.IO.StreamReader("E: \phone.txt")
For i = 1 To 20
q(i) = file.ReadLine() & vbNewLine
ComboBox2.Items.Add(q(i))
Next
ElseIf type = "Tablet" Then
ComboBox2.Items.Clear()
Dim file As New System.IO.StreamReader("E:\tablet.txt")
For i = 1 To 20
q(i) = file.ReadLine() & vbNewLine
ComboBox2.Items.Add(q(i))
Next
ElseIf type = "Desktop computer" Then
ComboBox2.Items.Clear()
Dim file As New System.IO.StreamReader("E:\pc.txt")
For i = 1 To 20
q(i) = file.ReadLine() & vbNewLine
ComboBox2.Items.Add(q(i))
Next
ElseIf type = "Laptop" Then
ComboBox2.Items.Clear()
Dim file As New System.IO.StreamReader("E:\laptop.txt")
For i = 1 To 20
q(i) = file.ReadLine() & vbNewLine
ComboBox2.Items.Add(q(i))
Next
'Else
'Dim objwriter As System.IO.StreamWriter
'objwriter = My.Computer.FileSystem.OpenTextFileWriter("E:\unknown.txt", True)
'File.AppendText("type:" And ComboBox1.Text And "make" & ComboBox2.Text And "model: " & ComboBox3.Text And "version: " And TextBox2.Text & "memory" And TextBox3.Text)
End If
End Sub
However,the code won't work to change what is in the 3rd box. I have repeated the following code for each option:
Private Sub ComboBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox3.SelectedIndexChanged
Dim type As String = ComboBox1.SelectedItem
Dim make As String = ComboBox2.SelectedItem
Dim model As String = ComboBox3.SelectedItem
Dim version As String = TextBox2.Text
Dim memory As String = TextBox3.Text
Dim problem As String = TextBox4.Text
If type = "Phone" Then
If make = "apple" Then
ComboBox2.Items.Clear()
Dim file As New System.IO.StreamReader("E:\apple.txt")
For i = 1 To 20
q(i) = file.ReadLine() & vbNewLine
ComboBox3.Items.Add(q(i))
Next
ElseIf make = "samsung" Then
ComboBox2.Items.Clear()
Dim file As New System.IO.StreamReader("E:\samsung.txt")
For i = 1 To 20
q(i) = file.ReadLine() & vbNewLine
ComboBox3.Items.Add(q(i))
Next
ElseIf make = "htc" Then
ComboBox2.Items.Clear()
Dim file As New System.IO.StreamReader("E:\htc.txt")
For i = 1 To 20
q(i) = file.ReadLine() & vbNewLine
ComboBox3.Items.Add(q(i))
Next
ElseIf make = "Nokia" Then
ComboBox2.Items.Clear()
Dim file As New System.IO.StreamReader("E:\Nokia.txt")
For i = 1 To 20
q(i) = file.ReadLine() & vbNewLine
ComboBox3.Items.Add(q(i))
Next
ElseIf make = "Blackberry" Then
ComboBox2.Items.Clear()
Dim file As New System.IO.StreamReader("E:\blackberry.txt")
For i = 1 To 20
q(i) = file.ReadLine() & vbNewLine
ComboBox3.Items.Add(q(i))
Next
I have checked the obvious problems like putting the wrong text file names and capital letters etc, but can't get this to work whatever I do.
Does anyone know why the third combobox remains blank even when both conditions are met (both combobox1 and 2 have the right thing selected)? Any suggestion would be much appreciated.
Firstly I suspect that this code :-
Dim type As String = ComboBox1.SelectedItem.ToString
Dim make As String = ComboBox2.SelectedItem.ToString
Dim model As String = ComboBox3.SelectedItem.ToString
Dim version As String = TextBox2.Text
Dim memory As String = TextBox3.Text
Dim problem As String = TextBox4.Text
shouldn't be in each if your events. They should really be placed somewhere that executes after all the information has been chosen yes?
OK for a start paste this into a text file called "device type.txt"
Phone,E:\phone.txt
Tablet,E:\tablet.txt
Desktop Computer,E:\pc.txt
Laptop,E:\laptop.txt
Then edit your phones.txt file and the rest of the above files to match that format e.g this phone.txt file
Apple,E:\apple.txt
Samsung,E:\samsung.txt
Htc,E:\htc.txt
Nokia,E\nokia.txt
Blackberry,E:\blackberry.txt
and so on for each item that links to another file. For the last files in the tree - which I presume are the files containing a list of the models for each brand of phone, just leave them as a simple list. No commas or anything after each model.
Use this code to do the populating of each ComboBox
Private Sub PopulateComboBox(ByRef cboBox As ComboBox, ByVal itemSource As String)
RemoveHandler ComboBox1.SelectedIndexChanged, AddressOf ComboBox1_SelectedIndexChanged
RemoveHandler ComboBox2.SelectedIndexChanged, AddressOf ComboBox2_SelectedIndexChanged
RemoveHandler ComboBox3.SelectedIndexChanged, AddressOf ComboBox3_SelectedIndexChanged
Dim devices As New List(Of item)
Dim csvFlag As Boolean = False
cboBox.Items.Clear()
Using MyReader As New Microsoft.VisualBasic.
FileIO.TextFieldParser(itemSource)
If MyReader.ReadLine.Contains(",") Then csvFlag = True
End Using
Using MyReader As New Microsoft.VisualBasic.
FileIO.TextFieldParser(itemSource)
If csvFlag Then
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
End If
Dim currentRow As String() = {"", ""}
While Not MyReader.EndOfData
Try
If csvFlag Then
currentRow = MyReader.ReadFields()
Dim tempItem As New item
tempItem.item = currentRow(0)
tempItem.fileName = currentRow(1)
devices.Add(tempItem)
Else
currentRow(0) = MyReader.ReadLine
Dim tempItem As New item
tempItem.item = currentRow(0)
tempItem.fileName = ""
devices.Add(tempItem)
End If
Catch ex As Microsoft.VisualBasic.
FileIO.MalformedLineException
MsgBox("Line " & ex.Message & "is not valid and will be skipped.")
End Try
End While
End Using
If csvFlag Then
cboBox.DataSource = devices
cboBox.DisplayMember = "item"
cboBox.ValueMember = "fileName"
Else
cboBox.DataSource = devices
cboBox.DisplayMember = "item"
cboBox.ValueMember = "item"
End If
AddHandler ComboBox1.SelectedIndexChanged, AddressOf ComboBox1_SelectedIndexChanged
AddHandler ComboBox2.SelectedIndexChanged, AddressOf ComboBox2_SelectedIndexChanged
AddHandler ComboBox3.SelectedIndexChanged, AddressOf ComboBox3_SelectedIndexChanged
End Sub
What it does is firstly check to see if the file being read is a comma-delimited file.
If it is delimited, it will read the file referred to in itemSource and expect a pair of values. The first value is what you see in the box(the DisplayMember), and the second value is what clicking on the box actually returns(the ValueMember)
If the file isn't comma-delimited, it will just read each line and add it to the combobox so that it acts normally (this will be important for the last files in the tree)
Next you need these methods for the ComboBoxes
Private Sub PopulateComboBox1()
PopulateComboBox(ComboBox1, "E:\device type.txt")
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
PopulateComboBox(ComboBox2, ComboBox1.SelectedValue.ToString)
End Sub
Private Sub ComboBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox2.SelectedIndexChanged
PopulateComboBox(ComboBox3, ComboBox2.SelectedValue.ToString)
End Sub
Private Sub ComboBox3_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox3.SelectedIndexChanged
PopulateComboBox(ComboBox3, ComboBox2.SelectedValue.ToString)
End Sub
Call the method to populate Combobox1 possibly in the form's load event.

How do I read contents of a DataTable and assign them to other controls?

Good morning,
I've been up all night trying to figure this out on my own without bugging anybody else, but I can't.
I've been successful in querying my MySQL database and gotten a set of records into a DataTable (dbTable). During debugging, I can see its contents so I know the data is there. Initially, the DataTable is used to populate a ListView control I have on my form.
When I select a record, I want the contents of the DataTable (or the query I just ran) to be assigned to some TextBox controls. I can't seem to figure out how to do this. Any help would be greatly appreciated.
UPDATE TO ADD IMAGES:
I'm hoping these screenshots will give an idea of what I'm looking to do. The first image shows what happens after an account number has been entered. The second box shows a Groupbox expanded to reveal the form fields after a record has been selected in the ListView.
The control names are: TextBoxCustomer, TextBoxLastName, TextBoxFirstName, ComboBoxSalutation, ComboBoxCardType, TextBoxCard.Text, TextBoxExpireMonth, TextBoxExpireYear, TextBoxCVV2.
The field names in the DataTable (dbTable) are: nameCOMPANY, nameLAST, nameFIRST, nameSALUTATION, ccType, ccNumber, ccExpireMonth, ccExpireYear, ccCode.
IMAGE 1:
IMAGE 2:
Have you tried this?
TextBox1.Text = dbTable.Rows(0)("ColumnName").ToString()
TextBox2.Text = dbTable.Rows(1)("OtherColumnName").ToString()
You can also do this:
Dim row as DataRow = dbTable.Rows(0)
TextBox1.Text = row("ColumnName").ToString()
row = dbTable.Rows(1)
TextBox2.Text = row("OtherColumnName").ToString()
You could also DataBind to a DataGrid (or similar control) using dbTable as the DataSource and then set the DataGrid.EditMode to True. This would create the textbox controls for you.
UPDATE:
Try something like this to bind your textboxes to the selected values of your ListView:
Private Sub ListView1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ListView1.SelectedIndexChanged
Dim item As ListViewItem = Nothing
Dim tb As TextBox = Nothing
Dim i As Integer = 0
For Each item In ListView1.SelectedItems
tb = Me.Controls.Find("TextBox" & i.ToString, True)(0)
If tb IsNot Nothing Then
tb.Text = item.Text
End If
i += 1
Next
End Sub
UPDATE:
This is a little more error-proof, but this routine will only work if your textboxes are named TextBox1, TextBox2, TextBox3, etc.:
Private Sub ListView1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ListView1.SelectedIndexChanged
Dim item As ListViewItem = Nothing
Dim found() As Control = Nothing
Dim tb As TextBox = Nothing
Dim i As Integer = 0
For Each item In ListView1.SelectedItems
found = Me.Controls.Find("TextBox" & i.ToString, True)
If found.Length > 0 Then
tb = TryCast(found(0), TextBox)
Else
tb = Nothing
End If
If tb IsNot Nothing Then
tb.Text = item.Text
End If
i += 1
Next
End Sub
UPDATE:
Okay, thanks to the screenshots, I am assuming that your ListView.MultiSelect = False, so only one item can be selected at a time. Given that, the following should work as long as the textboxes and ListView columns are named correctly:
Private Sub ListView1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ListView1.SelectedIndexChanged
Dim item As ListViewItem = Nothing
If ListView1.SelectedItems.Count = 1 Then
item = ListView1.SelectedItems(0)
txtCardNumber.Text = item.SubItems("CARD NUMBER")
txtCardExpirationMonth.Text = item.SubItems("EXP MO")
txtCardExpirationYear.Text = item.SubItems("EXP YEAR")
End If
End Sub
Hello guys/gals,
With tremendous assistance from Pete, I was able to modify the suggested answer and I achieved the desired solution. To prevent the horizontal scrollbars from displaying, I didn't add columns to the Listview (from the Designer). Instead, I added the fields to the Listview programatically - this way they were available for selection.
The main trouble I ran into was figuring out the Index numbers of the fields. I had to debug several times to figure out what the numbers were - so if anybody knows of a better way please do share.
Here're the two codes I used (thanks Pete):
Private Sub loadCard()
Try
'FOR MySQL DATABASE USE
Dim dbQuery As String = ""
Dim dbCmd As New MySqlCommand
Dim dbAdapter As New MySqlDataAdapter
Dim dbTable As New DataTable
Dim i As Integer
If dbConn.State = ConnectionState.Closed Then
dbConn.ConnectionString = String.Format("Server={0};Port={1};Uid={2};Password={3};Database=accounting", FormLogin.ComboBoxServerIP.SelectedItem, My.Settings.DB_Port, My.Settings.DB_UserID, My.Settings.DB_Password)
dbConn.Open()
End If
dbQuery = "SELECT *" & _
"FROM cc_master INNER JOIN customer ON customer.accountNumber = cc_master.customer_accountNumber " & _
"WHERE customer.accountNumber = '" & TextBoxAccount.Text & "'"
With dbCmd
.CommandText = dbQuery
.Connection = dbConn
End With
With dbAdapter
.SelectCommand = dbCmd
.Fill(dbTable)
End With
ListViewCard.Items.Clear()
For i = 0 To dbTable.Rows.Count - 1
With ListViewCard
.Items.Add(dbTable.Rows(i)("ccID"))
With .Items(.Items.Count - 1).SubItems
.Add(dbTable.Rows(i)("ccNumber"))
.Add(dbTable.Rows(i)("ccExpireMonth"))
.Add(dbTable.Rows(i)("ccExpireYear"))
.Add(dbTable.Rows(i)("ccCode"))
.Add(dbTable.Rows(i)("ccType"))
.Add(dbTable.Rows(i)("ccAuthorizedUseStart"))
.Add(dbTable.Rows(i)("ccAuthorizedUseEnd"))
.Add(dbTable.Rows(i)("nameCOMPANY"))
.Add(dbTable.Rows(i)("nameSALUTATION"))
.Add(dbTable.Rows(i)("nameLAST"))
.Add(dbTable.Rows(i)("nameFIRST"))
End With
End With
Next
If dbTable.Rows.Count = 0 Then
LabelNoCard.Visible = True
LabelNoCard.Focus()
TextBoxAccount.Focus()
Me.Refresh()
Else
If dbTable.Rows.Count > 1 Then
LabelNoCard.Visible = False
LabelMultipleCards.Visible = True
ListViewCard.Visible = True
Me.Refresh()
End If
End If
Catch ex As MySqlException
MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _
vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.")
End Try
dbConn.Close()
End Sub
Here's the second one:
Private Sub ListViewCard_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListViewCard.SelectedIndexChanged
GroupBox2.Visible = True
Dim item As ListViewItem = Nothing
If ListViewCard.SelectedItems.Count = 1 Then
item = ListViewCard.SelectedItems(0)
TextBoxCustomer.Text = item.SubItems(8).Text
TextBoxLastName.Text = item.SubItems(10).Text
TextBoxFirstName.Text = item.SubItems(11).Text
ComboBoxSalutation.Text = item.SubItems(9).Text
ComboBoxCardType.Text = item.SubItems(5).Text
TextBoxCard.Text = item.SubItems(1).Text
TextBoxExpireMonth.Text = item.SubItems(2).Text
TextBoxExpireYear.Text = item.SubItems(3).Text
TextBoxCVV2.Text = item.SubItems(4).Text
DateTimePickerStartDate.Text = item.SubItems(6).Text
DateTimePickerEndDate.Text = item.SubItems(7).Text
End If
End Sub

Backgroundworker doesn't work... VB.Net

this is my code:
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
For i = 0 To 1000
Dim inum As String = i & "0"
Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create("http://www.google.nl/search?q=site:" & combobox1.Text & "&hl=nl&start=" & inum)
Dim response As System.Net.HttpWebResponse = request.GetResponse
Dim sr As System.IO.StreamReader = New System.IO.StreamReader(response.GetResponseStream())
Dim sourcecode As String = sr.ReadToEnd
Dim search As String = combobox1.Text
Dim r As New System.Text.RegularExpressions.Regex("http://" & search & "/\w*")
Dim matches As MatchCollection = r.Matches(sourcecode)
For Each itemcode As Match In matches
Dim item As String = (itemcode.ToString.Split("""").GetValue(0))
Dim url As New Net.WebClient
Dim str As String = url.DownloadString("http://www.prcheck.nl/results.php?url=" & item)
If str.Contains(">0/10") Then
ListBox1.Items.Add("(0/10) " & item)
ElseIf str.Contains("1/10") Then
ListBox1.Items.Add("(1/10) " & item)
ElseIf str.Contains("2/10") Then
ListBox1.Items.Add("(2/10) " & item)
ElseIf str.Contains("3/10") Then
ListBox1.Items.Add("(3/10) " & item)
ElseIf str.Contains("4/10") Then
ListBox1.Items.Add("(4/10) " & item)
ElseIf str.Contains("5/10") Then
ListBox1.Items.Add("(5/10) " & item)
ElseIf str.Contains("6/10") Then
ListBox1.Items.Add("(6/10) " & item)
ElseIf str.Contains("7/10") Then
ListBox1.Items.Add("(7/10) " & item)
ElseIf str.Contains("8/10") Then
ListBox1.Items.Add("(8/10) " & item)
ElseIf str.Contains("9/10") Then
ListBox1.Items.Add("(9/10) " & item)
ElseIf str.Contains("10/10") Then
ListBox1.Items.Add("(10/10) " & item)
Else
ListBox1.Items.Add("(0/10) " & item)
End If
Label2.Text = ListBox1.Items.Count
Next
If Not sourcecode.Contains("<b>Volgende</b>") Then
MsgBox("")
Exit For
End If
Next
End Sub
and combobox1.text = www.google.nl ( example )
at button 1 the code is:
BackgroundWorker1.RunWorkerAsync()
and if backgroundworker is done:
Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
MsgBox("Done")
End Sub
if i click button 1, i get within a half second the message: Done
what's wrong with the code??
if i put the code inside backgroundworker1 just in button1 it works but goes really slow..
You can only update the UI from within the main application thread, in this case you're attempting to do it via a background thread that has been created by the background worker which will throw an exception as you've found.
What you'll need to do it run the code which adds to the ListBox on the main thread which you can do via BeginInvoke and a custom delegate which takes the item you want to add as a parameter, the delegate can then add the item to list box - there's an example of how to do this in the docs for BeginInvoke.
I would return a list or array of items to be added from the background worker and then fill the ListBox in the RunWorkerCompleted event handler.