none
Vb.net function RRS feed

  • Question

  • Hi,

    I need your help.

    I'm new to vb and i'm trying to call a function

       Public Function words(ByVal Query As String) As List(Of String)
            Dim NewList As New List(Of String)
            Try
                Dim Result As String = New WebClient() With {.Proxy = Nothing, .Encoding = Encoding.UTF8}.DownloadString("http://mylink) some code....
                For Each MyItem In Split(Result, """,""")
                    NewList.Add(MyItem)
                Next
            Catch ex As Exception : End Try
            Return NewList
          
        End Function

    now to call the function to have the result of newlist what can I do?

    Iìm trying to add those result inside a string collection.

    Dim MySource As New AutoCompleteStringCollection()

    thank you for your help

    Friday, May 19, 2017 10:40 AM

All replies

  • Hi,

    I need your help.

    I'm new to vb and i'm trying to call a function

       Public Function words(ByVal Query As String) As List(Of String)
            Dim NewList As New List(Of String)
            Try
                Dim Result As String = New WebClient() With {.Proxy = Nothing, .Encoding = Encoding.UTF8}.DownloadString("http://mylink) some code....
                For Each MyItem In Split(Result, """,""")
                    NewList.Add(MyItem)
                Next
            Catch ex As Exception : End Try
            Return NewList
          
        End Function

    now to call the function to have the result of newlist what can I do?

    Iìm trying to add those result inside a string collection.

    Dim MySource As New AutoCompleteStringCollection()

    thank you for your help

    If it's just text, you can use a streamreader and read the lines:

        ''' <summary>
        ''' Returns a List(Of String) from each line in the text file.
        ''' </summary>
        ''' <param name="url">The URL of the remote text file.</param>
        ''' <param name="skipBlankLines">Indicate whether or not to skip blank lines.</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Private Function GetTextFromURL(ByVal url As String, _
                                           Optional ByVal skipBlankLines As Boolean = False) _
                                           As List(Of String)
    
            Dim retVal As New List(Of String)
    
            Try
                Dim request As WebRequest = WebRequest.Create(url)
    
                Using response As HttpWebResponse = DirectCast(request.GetResponse, HttpWebResponse)
                    Using dataStream As Stream = response.GetResponseStream
                        Using rdr As New StreamReader(dataStream)
                            Do While rdr.Peek() >= 0
                                Dim itm As String = rdr.ReadLine.Trim
                                If skipBlankLines Then
                                    If itm <> "" Then
                                        retVal.Add(itm)
                                    End If
                                Else
                                    retVal.Add(itm)
                                End If
                            Loop
                        End Using
                    End Using
                End Using
    
            Catch ex As Exception
                retVal = Nothing
            End Try
    
            Return retVal
    
        End Function


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Friday, May 19, 2017 11:11 AM
  • You need to indicate what you are after with the resulting string and even a sampling of the data otherwise I would say you are looking at something like this which means you need to figure out how to parse the data.

    Using client As New WebClient With {.Encoding = Encoding.UTF8}
        Dim value As String = client.DownloadString("https://Google.com")
        Console.WriteLine(value.Substring(0, 140))
    End Using


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Friday, May 19, 2017 11:19 AM
    Moderator
  • Hi,

    I need your help.

    I'm new to vb and i'm trying to call a function

       Public Function words(ByVal Query As String) As List(Of String)
            Dim NewList As New List(Of String)
            Try
                Dim Result As String = New WebClient() With {.Proxy = Nothing, .Encoding = Encoding.UTF8}.DownloadString("http://mylink) some code....
                For Each MyItem In Split(Result, """,""")
                    NewList.Add(MyItem)
                Next
            Catch ex As Exception : End Try
            Return NewList
          
        End Function

    now to call the function to have the result of newlist what can I do?

    Iìm trying to add those result inside a string collection.

    Dim MySource As New AutoCompleteStringCollection()

    thank you for your help

    Hi

    What do you intend to do with the 'MySource' ?

    I can't help but think you are maybe not actually wanting the data as a AutoCompleteStringCollection.

    Here is some code that gets you the data in a AutoCompleteStringCollection, and in the example, uses it to populate a ComboBox (not the way I would choose to do this however). This example just uses a string for the data instead of downloading it.

    Option Strict On
    Option Explicit On
    Public Class Form1
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            ' simulate incoming data (just a plain string here)
            ' yours would be the data from the downloaded string
            Dim test As String = "test,data,a,bc,def,gh,i,jk,lmno,pq,rst,uvwxyz"
            '--------------------------------------
    
            Dim MySource As New AutoCompleteStringCollection()
            MySource.AddRange(words(test).ToArray)
    
            '--------------------------------------
            ' for example, add data to a ComboBox
            ComboBox1.DataSource = MySource
            ComboBox1.AutoCompleteSource = AutoCompleteSource.ListItems
            ComboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend
    
        End Sub
        Public Function words(s As String) As List(Of String)
            Dim NewList As New List(Of String)
            Try
                ' you add your own data string here
                For Each MyItem In Split(s, ",")
                    NewList.Add(MyItem)
                Next
            Catch ex As Exception
                ' should never leave an empty catch
                Stop
            End Try
            ' sort data (if needed)
            NewList.Sort()
            Return NewList
        End Function
    End Class


    Regards Les, Livingston, Scotland

    Friday, May 19, 2017 1:29 PM
  • Hi,

    I need your help.

    I'm new to vb and i'm trying to call a function

    Catch is not meant to put your head in the water and drown.

    The general concept of your function is well. However, this piece of code makes probably that the New list is always empty and then you return that empty list. 

    Catch ex As Exception : End Try

    Remove it, and then look at why it gives an error. Solve that and then your function can return a full list. 

    I see that many have given you suggestions around that in this thread. 



    Success
    Cor

    Friday, May 19, 2017 1:48 PM
  • Thank you for your help.

    I just did in this way:

    propriety of txtsearch
    autocompletesource =customsource
    autocompletemode=suggest

     
    declared before
    dim autowords As New AutoCompleteStringCollection
    
    Private Sub txtSearch_TextChanged(sender As Object, e As EventArgs) Handles txtSearch.TextChanged
    
            If txtSearch.Text.Length > 0 Then
               autowords.AddRange((words(txtSearch.Text)).ToArray)
                txtSearch.AutoCompleteCustomSource = autowords
    
            End If
        End Sub
    
    and this is the function:
    
     Public Function Suggestions(ByVal Query As String) As List(Of String)
            Dim NewList As New List(Of String)
            Try
                Dim Result As String = New WebClient() With {.Proxy = Nothing, .Encoding = Encoding.UTF8}.DownloadString("http://mysitehere")
                For Each MyItem In Split(Result, """,""")
                    NewList.Add(MyItem)
                Next
            Catch ex As Exception : End Try
            Return NewList
        End Function

    Only problem that have now is that sometimes it give me this error

    :'System.AccessViolationException' in System.Windows.Forms.dll
    it try to read or write protected source


    Friday, May 19, 2017 2:08 PM
  • Thank you for your help.

    Please make it obvious who you're talking to; we don't all see this forum the same way.

    *****

    What are you trying to accomplish with this?


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Friday, May 19, 2017 2:17 PM
  • Thank you for your help.

    Please make it obvious who you're talking to; we don't all see this forum the same way.

    *****

    What are you trying to accomplish with this?


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Hi Frank,

    I wrote thanks for courtesy and because all you tried to help me and this is important.  But no one gave a valid answer to my problem.
    What I wrote was my personal test.

    I wrote thanks for courtesy, but no one gave a valid answer to my problem
    Friday, May 19, 2017 2:30 PM

  • Hi Frank,

    I wrote thanks for courtesy and because all you tried to help me and this is important.  But no one gave a valid answer to my problem.
    What I wrote was my personal test.

    I wrote thanks for courtesy, but no one gave a valid answer to my problem

    I understand. We're not done yet and I feel sure that an answer will be forthcoming.

    On the website, is there a text file that has lines of text or just what's there? That's a good place to start.


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Friday, May 19, 2017 2:32 PM
  • Hi Frank,

    the problem is not on data of site,

    that populate me the txtsearch in good way  but if I type to fast the letters it give me error 

    System.AccessViolationException' in System.Windows.Forms.dll
    it try to read or write protected source

     maybe the request to the website take some seconds and for this the customsource is not available.

    I need so to find I way to wait until the request from website arrive but not to block me typing letters to search box--> (txtsearch)

    for each letter typed it call this function, maybe textchanged is not the best way but also keyenter give me this error.

    Again I really appreciate your help, thanks

    I really appreciate your help
    Friday, May 19, 2017 2:42 PM
  • Hi Frank,

    the problem is not on data of site,

    that populate me the txtsearch in good way  but if I type to fast the letters it give me error 

    System.AccessViolationException' in System.Windows.Forms.dll
    it try to read or write protected source

     maybe the request to the website take some seconds and for this the customsource is not available.

    I need so to find I way to wait until the request from website arrive but not to block me typing letters to search box--> (txtsearch)

    for each letter typed it call this function, maybe textchanged is not the best way but also keyenter give me this error.

    Again I really appreciate your help, thanks

    I really appreciate your help

    Ok we're not talking about the downloading or any of that then. That's where I was confused.

    The way you describe it though, that actually is the problem: You keep going back and re-populating it.

    Instead of that, set up a class-scoped List(Of String). In the form's .Load event, send it to your method to then populate that List(Of String) - or a string array is all you need - then set that for the .AutoComplete source.

    Make sense?


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Friday, May 19, 2017 2:56 PM
  • I understand,

    but if I insert on load event can't know what is typed on the txtsearch.

    so the variable autowords will be empty.

    Give me the possibility to try to explain better what I'm trying to do.

    the txtsearch -->textbox will be like google search.

    if you type a letter on google it give you the suggest words to search.

    my txtsearch need to do the same only that sources are on my website.

    So what I'm trying to do is:

    on textchanged event it call the function and if find a word that contains that letter, download the result and populate the list. then added the list to my customsource to display on txtsearch  like suggestion.

    Again, everything goes fine except if as soon as I load form type to write on txtsearch goes on error or if I type to fast letters.

    Do you know or do you thing is possible to intercept this error?

    Friday, May 19, 2017 3:12 PM
  • I understand,

    but if I insert on load event can't know what is typed on the txtsearch.

    so the variable autowords will be empty.

    Give me the possibility to try to explain better what I'm trying to do.

    the txtsearch -->textbox will be like google search.

    if you type a letter on google it give you the suggest words to search.

    my txtsearch need to do the same only that sources are on my website.

    So what I'm trying to do is:

    on textchanged event it call the function and if find a word that contains that letter, download the result and populate the list. then added the list to my customsource to display on txtsearch  like suggestion.

    Again, everything goes fine except if as soon as I load form type to write on txtsearch goes on error or if I type to fast letters.

    Do you know or do you thing is possible to intercept this error?

    I'm not sure that we're connecting here, but I've uploaded a small text file to my site here:

    http://www.fls-online.net/VBNet_Forum/Example.txt

    I'll use that to then create the source of the AutoComplete of TextBox1:

    Option Strict On
    Option Explicit On
    Option Infer Off
    
    Imports System.Net
    Imports System.IO
    
    Public Class Form1
        Private words As New AutoCompleteStringCollection()
    
    
        Private Sub Form1_Load(sender As System.Object, _
                               e As System.EventArgs) _
                               Handles MyBase.Load
    
            Const url As String = _
                "http://www.fls-online.net/VBNet_Forum/Example.txt"
    
            Dim wordList As List(Of String) = GetTextFromURL(url, True)
    
            If wordList IsNot Nothing AndAlso wordList.Count > 0 Then
                words.AddRange(wordList.ToArray)
    
                With TextBox1
                    .AutoCompleteCustomSource = words
                    .AutoCompleteMode = AutoCompleteMode.SuggestAppend
                    .AutoCompleteSource = AutoCompleteSource.CustomSource
                End With
            End If
    
        End Sub
    
    
    
        ''' <summary>
        ''' Returns a List(Of String) from each line in the text file.
        ''' </summary>
        ''' <param name="url">The URL of the remote text file.</param>
        ''' <param name="skipBlankLines">Indicate whether or not to skip blank lines.</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Private Function _
            GetTextFromURL(ByVal url As String, _
                           Optional ByVal skipBlankLines As Boolean = False) _
                           As List(Of String)
    
            Dim retVal As New List(Of String)
    
            Try
                Dim request As WebRequest = WebRequest.Create(url)
    
                Using response As HttpWebResponse = DirectCast(request.GetResponse, HttpWebResponse)
                    Using dataStream As Stream = response.GetResponseStream
                        Using rdr As New StreamReader(dataStream)
                            Do While rdr.Peek() >= 0
                                Dim itm As String = rdr.ReadLine.Trim
                                If skipBlankLines Then
                                    If itm <> "" Then
                                        retVal.Add(itm)
                                    End If
                                Else
                                    retVal.Add(itm)
                                End If
                            Loop
                        End Using
                    End Using
                End Using
    
            Catch ex As Exception
                retVal = Nothing
            End Try
    
            Return retVal
    
        End Function
    End Class

    Is that what you want or ... no?


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Friday, May 19, 2017 3:23 PM
  • It works fine because you download source of webpage on load event.

    and you have understand good my problem.

    It would be simple if the source was static, to my site I send a query request to my database so everytime I type a letter on my txtsearch it call the function to download source. because data will change in base of my text request.

    for this it give me this error if I type fast letter

    Additional Information: Attempting to read or write protected memory. Often this condition indicates that other parts of the memory are damaged.
    Thank you Frank for your time.

    Friday, May 19, 2017 3:46 PM
  • ... I send a query request to my database ...

    Oh ok - I didn't know that's what was behind all of this.

    Karen and Cor are the right people to help you with this then; I'm not a database person at all.

    Be patient. :)


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Friday, May 19, 2017 3:49 PM
  • It works fine because you download source of webpage on load event.

    and you have understand good my problem.

    It would be simple if the source was static, to my site I send a query request to my database so everytime I type a letter on my txtsearch it call the function to download source. because data will change in base of my text request.

    for this it give me this error if I type fast letter

    Additional Information: Attempting to read or write protected memory. Often this condition indicates that other parts of the memory are damaged.
    Thank you Frank for your time.

    I hate that nobody has replied back, but I'll offer my suggestion anyway:

    I suspect that you'll send up doing, effectively, what I did with my example; I'm not sure what you have set up with your database, but AutoComplete is based on a source being in memory.

    If you're changing that a lot then it's bound to cause some issues and I suspect that's what you're dealing with.


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Saturday, May 20, 2017 12:55 PM