Listview:displaying froma text file

Johnson

Well-known member
Joined
Mar 6, 2009
Messages
158
Programming Experience
Beginner
Hello, on my application i have a username and password form that saves the username & password

It's not meant to be secure, and it writes to a text file displaying as so

VB.NET:
Johnson:password1
Newname:password2
Newname2:password3

here is the code

VB.NET:
    Private Sub cmdPostAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdPostAdd.Click
        'Add new username and password

        If txtPostName.Text <> "" And txtPostValue.Text <> "" Then
            Dim liNew As ListViewItem = lvPost.Items.Add(txtPostName.Text)
            liNew.SubItems.Add(txtPostValue.Text)
            txtPostName.Text = ""
            txtPostValue.Text = ""
            Dim i As Integer = 0
            Dim sTemp As String = ""

            ' Write All Items and subitems to a file
            With lvPost
                .View = View.Details
                For i = 0 To .Items.Count - 1
                    ' Collect Item and subitems as comma separated elements 
                    ' sTemp += .Items(i).Text & ","
                    sTemp += .Items(i).SubItems(0).Text & ":"
                    sTemp += .Items(i).SubItems(1).Text & vbNewLine
                Next
            End With
            My.Computer.FileSystem.WriteAllText("C:\UIS.txt", sTemp, False)

        End If
    End Sub

This all works fine, but i have no idea how to reload this information when the form loads.

Obviously it needs to read the string, the seperate the username and password.

i have been trying for hours

also is it possible to password char the password section in the listview? at the moment it can be read.

thanks
 
I saw someone else ask a similar question recently and I pose the same response to you: what's the point of displaying the passwords at all if you're not going to display them? If the user can't read the text of the password then there isn't any point displaying it.
 
Because the passwords are for a login, which can be changed the they need to be editable.

not really helping my cause that is it :D
 
You can't edit data in a ListView anyway, except the first column. It's a very bad idea to do what you're trying to do. If the user can edit the passwords then why mask them? If you do mask them then the user can't see what they're typing in. Have you ever created a password for an account anywhere? Notice how they get you to enter it twice so that if you make a typo it gets caught? If you just display the password once and mask it then the user could edit it and make a typo and then they won't be able to log in to that account.

A far better idea is to not show the password at all in your table and, if it needs to be edited, open a dialogue that asks for the old password for confirmation, then asks for the new password twice, to protect against typos.
 
it's not a serious application mate, it's only for my use. I'm just new to vb and trying different things. Im just trying to make it look like something.

But the password is the least of it to me. i still havent not found on the net how to reload my information into the listview.

it's displaye din the textfile

name:password
name:password

etc. i gather it into a string with

VB.NET:
        If File.Exists("C:\Uis\User.txt") Then
            'Load user accounts
            Dim sTemp As String
            sTemp = My.Computer.FileSystem.ReadAllText("C:\Uis\User.txt")


            Dim sLines() As String
            Dim NewLn(1) As String
            NewLn(0) = vbNewLine  
            Dim i As Integer = 0
            Dim itmx As New ListViewItem

            sLines = sTemp.Split(NewLn, StringSplitOptions.None)
            For i = 0 To sLines.Count - 1
            ' split string and add to listview here
            Next
        End If

But how do i split this information?

It needs to ignore the : obviously
 
Last edited:
Rather than calling ReadAllText and then splitting it into lines, you should just call File.ReadAllLines. Better still, use a TextFieldParser to read a delimited file record by record, field by field.

As for reloading a ListView, there's no magic to it. Reloading a ListView is EXACTLY the same loading it in the first place, except you clear it first.
 
But im not reloading it mate, iv never loaded it. I dont no how to load it.

because iv got to split the user anme and then password add username to the index the password to the subindex
 
Can we see your final code for opening the file and getting the data? If you can't load the data then what point knowing how to display the data in a ListView? If we know exactly how you're loading the data then we can provide a specific answer to the question of displaying that data in a ListView. Stick to one problem at a time and you'll avoid confusing yourself and us.
 
This is my code
VB.NET:
  Imports System.Text.RegularExpressions
Imports System
Imports System.IO

Public Class frmMain

    Inherits System.Windows.Forms.Form
    'Create a new Random class in VB.NET
    Dim RandomClass As New Random()

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        On Error GoTo err

        'Go to requested url
        Dim url As System.Uri = New System.Uri(txtRequest.Text)
        Me.WebBrowser1.Navigate(url)

err:

    End Sub

    Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Create projects dir
        Dim di As DirectoryInfo = New DirectoryInfo("c:\Uis")
        ' Determine whether the directory exists.
        If di.Exists Then
            'already exists.
        Else
            ' Try to create the directory.
            di.Create()
        End If

        If File.Exists("C:\Uis\User.txt") Then
            'Load user accounts
            Dim sTemp As String
            sTemp = My.Computer.FileSystem.ReadAllText("C:\Uis\User.txt")




        End If

        If File.Exists("C:\Uis\Agent.txt") Then
            'Load user agent
            Dim sTemp As String
            sTemp = My.Computer.FileSystem.ReadAllText("C:\Uis\Agent.txt")



        End If
        'Sort entrys in ascending order
        lvPost.Sorting = SortOrder.Ascending

        'Gather 

        'Reset txtH
        txtH.Text = ""

    End Sub


    Private Sub WebBrowser1_DocumentCompleted(ByVal sender As Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
        txtSource.Text = Me.WebBrowser1.Document.Body.InnerHtml
        txtRequest.Text = WebBrowser1.Url.ToString()
    End Sub





    Private Sub cmdPostAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdPostAdd.Click
        'check value

        If String.IsNullOrEmpty(txtPostName.Text) Then

            MessageBox.Show("Enter a username", "Invaild", MessageBoxButtons.OK, _
                            MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
            Exit Sub

        ElseIf String.IsNullOrEmpty(txtPostValue.Text) Then


            MessageBox.Show("Enter a password", "Invalid", MessageBoxButtons.OK, _
                            MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
            Exit Sub
        End If

        'Add new username and password

        If txtPostName.Text <> "" And txtPostValue.Text <> "" Then
            Dim liNew As ListViewItem = lvPost.Items.Add(txtPostName.Text)
            liNew.SubItems.Add(txtPostValue.Text)
            txtPostName.Text = ""
            txtPostValue.Text = ""
            Dim i As Integer = 0
            Dim sTemp As String = ""

            '************************************
            ' Write All Items and subitems to a file
            With lvPost
                .View = View.Details
                For i = 0 To .Items.Count - 1
                    ' Collect Item and subitems as comma separated elements 
                    ' sTemp += .Items(i).Text & ","
                    sTemp += .Items(i).SubItems(0).Text & ":"
                    sTemp += .Items(i).SubItems(1).Text & vbNewLine

                Next
            End With
            My.Computer.FileSystem.WriteAllText("C:\Uis\User.txt", sTemp, False)
            '***********************************

        End If
    End Sub









    Private Sub lvpost_SelectedIndexChanged(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles lvPost.SelectedIndexChanged

        'Display selected index in auth tab
        Dim SelectedItems As ListView.SelectedListViewItemCollection = _
            CType(sender, ListView).SelectedItems
        If (SelectedItems.Count > 0) Then

            txtAuthUsername.Text = SelectedItems(0).SubItems(0).Text
            txtAuthPassword.Text = SelectedItems(0).SubItems(1).Text

        End If
    End Sub

    Private Sub tpPost_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tpPost.Click

    End Sub



    Private Sub DeleteToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DeleteToolStripMenuItem.Click

        'Do you really want to remove the user account?
        Dim i As Integer
        Try
            For i = 0 To lvPost.Items.Count - 1
                If lvPost.Items(i).Selected Then Exit For
            Next
            If lvPost.Items.Count <> 0 Then
                If MessageBox.Show("Delete User Account " & lvPost.Items(i).Text & "?", "Deleting", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then
                    lvPost.Items.RemoveAt(i)

                End If
            End If
        Catch ex As Exception

        End Try

        tmr.Enabled = True
    End Sub

    Private Sub tmr_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmr.Tick
        Dim i As Integer = 0
        Dim sTemp As String = ""

        '************************************
        ' Write All Items and subitems to a file
        With lvPost
            .View = View.Details
            For i = 0 To .Items.Count - 1
                ' Collect Item and subitems as comma separated elements 
                ' sTemp += .Items(i).Text & ","
                sTemp += .Items(i).SubItems(0).Text & ":"
                sTemp += .Items(i).SubItems(1).Text & vbNewLine

            Next
        End With
        My.Computer.FileSystem.WriteAllText("C:\Uis\User.txt", sTemp, False)
        '***********************************
        tmr.Enabled = False
    End Sub

    Private Sub KillDatabaseToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles KillDatabaseToolStripMenuItem.Click
        If MessageBox.Show("Are you sure you want to delete the database? This cannot be recovered.", "Deleting", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then
            Dim Argument As String()
            Dim FileToBurn As String
            Dim i As Integer = 0

            Dim RandomNumber As Integer
            RandomNumber = RandomClass.Next()



            Argument = System.Environment.GetCommandLineArgs

            Do Until i = 10

                FileToBurn = "C:\Uis\User.txt" 'Argument(i)
                FileOpen(1, FileToBurn, OpenMode.Output)

                Print(1, RandomNumber, "***Over written data***", RandomNumber)

                FileClose(1)

                i = i + 1


            Loop

        End If
        'kill over passed file
        Dim ow As String
        ow = "C:\Uis\User.txt" 'Argument(i)
        Kill(ow)
    End Sub

 

  

    Private Sub btnAgent_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAgent.Click
        'check value

        If String.IsNullOrEmpty(txtAgentName.Text) Then

            MessageBox.Show("Enter a username", "Invaild", MessageBoxButtons.OK, _
                            MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
            Exit Sub

        ElseIf String.IsNullOrEmpty(txtAgentId.Text) Then


            MessageBox.Show("Enter a User-Agent", "Invalid", MessageBoxButtons.OK, _
                            MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
            Exit Sub
        End If

        'Add new username and password

        If txtAgentName.Text <> "" And txtAgentId.Text <> "" Then
            Dim liNew As ListViewItem = lvAgent.Items.Add(txtAgentName.Text)
            liNew.SubItems.Add(txtAgentId.Text)
            txtAgentName.Text = ""
            txtAgentId.Text = ""
            Dim i As Integer = 0
            Dim sTemp As String = ""

            '************************************
            ' Write All Items and subitems to a file
            With lvAgent
                .View = View.Details
                For i = 0 To .Items.Count - 1
                    ' Collect Item and subitems as comma separated elements 
                    ' sTemp += .Items(i).Text & ","
                    sTemp += .Items(i).SubItems(0).Text & ":"
                    sTemp += .Items(i).SubItems(1).Text & vbNewLine

                Next
            End With
            My.Computer.FileSystem.WriteAllText("C:\Uis\Agent.txt", sTemp, False)
            '***********************************
        End If
    End Sub

    Private Sub DeleteAgentToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DeleteAgentToolStripMenuItem.Click
        'Do you really want to remove the user account?
        Dim i As Integer
        Try
            For i = 0 To lvAgent.Items.Count - 1
                If lvAgent.Items(i).Selected Then Exit For
            Next
            If lvAgent.Items.Count <> 0 Then
                If MessageBox.Show("Delete User Agent? " & lvAgent.Items(i).Text & "?", "Deleting", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then
                    lvAgent.Items.RemoveAt(i)

                End If
            End If
        Catch ex As Exception

        End Try

        tmragent.Enabled = True
    End Sub

    Private Sub tmragent_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmragent.Tick
        Dim i As Integer = 0
        Dim sTemp As String = ""

        '************************************
        ' Write All Items and subitems to a file
        With lvAgent
            .View = View.Details
            For i = 0 To .Items.Count - 1
                ' Collect Item and subitems as comma separated elements 
                ' sTemp += .Items(i).Text & ","
                sTemp += .Items(i).SubItems(0).Text & ":"
                sTemp += .Items(i).SubItems(1).Text & vbNewLine

            Next
        End With
        My.Computer.FileSystem.WriteAllText("C:\Uis\Agent.txt", sTemp, False)
        '***********************************
        tmragent.Enabled = False
    End Sub

    Private Sub KillDatabaseToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles KillDatabaseToolStripMenuItem1.Click
        If MessageBox.Show("Are you sure you want to delete the database? This cannot be recovered.", "Deleting", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then
            Dim Argument As String()
            Dim FileToBurn As String
            Dim i As Integer = 0

            Dim RandomNumber As Integer
            RandomNumber = RandomClass.Next()



            Argument = System.Environment.GetCommandLineArgs

            Do Until i = 10

                FileToBurn = "C:\Uis\Agent.txt" 'Argument(i)
                FileOpen(1, FileToBurn, OpenMode.Output)

                Print(1, RandomNumber, "***Over written data***", RandomNumber)

                FileClose(1)

                i = i + 1


            Loop

        End If
        'kill over passed file
        Dim ow As String
        ow = "C:\Uis\Agent.txt" 'Argument(i)
        Kill(ow)
    End Sub

    Private Sub ContextMenuStrip2_Opening(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles ContextMenuStrip2.Opening

    End Sub

    Private Sub lvAgent_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lvAgent.SelectedIndexChanged
        'Display selected user agent in Useragent field
        Dim SelectedItems As ListView.SelectedListViewItemCollection = _
            CType(sender, ListView).SelectedItems
        If (SelectedItems.Count > 0) Then
            Dim UserAgent
            UserAgent = SelectedItems(0).SubItems(0).Text & ":" & SelectedItems(0).SubItems(1).Text
            txtUserAgent.Text = UserAgent
        End If
    End Sub

   

End Class
 
Well i finally got there, if any one else wants to know how

VB.NET:
        If File.Exists("C:\Uis\User.txt") Then
            'Load user accounts
            Dim sr As StreamReader = New StreamReader("C:\Uis\User.txt")
            Dim sInput As String = ""
            Dim ThisRow() As String
            Dim sData() As String
            Dim i As Integer
            '//=Read all Data into sInput
            Do While sr.Peek >= 0
                sInput = sInput & sr.ReadLine & ControlChars.CrLf
            Loop

            ThisRow = Split(sInput, vbCrLf)

            For i = 0 To UBound(ThisRow) - 1
                sData = Split(ThisRow(i), ",")
                Dim lsvi As New ListViewItem(sData, 2)
                lvPost.Items.Add(lsvi)
            Next

            lvPost.Sort()
            sr.Close()


        End If
 
OK, let's examine what you're doing there. You are opening the file and reading it line by line and as you do that, you combine those lines back into a single string. If you want a single string then you shouldn't read the file line by line. You should just call ReadToEnd to get the entire contents.

Once you've got the file contents into that single string you then break it up into individual lines. You read the file as individual lines in the first place so, if you want individual lines, why are you combining them into a single string? Why don't you just use each line as you read it?
VB.NET:
Using reader As New StreamReader("file path here")
    Do Until reader.EndOfStream
        myListView.Items.Add(reader.ReadLine().Split(","c))
    Loop
End Using
 
I don't know why i am mate, I found that on planet source. and since i have been trying to do this for 4 days and it worked i guess i didnt really look at it properly.

I get the error Error
VB.NET:
1	Overload resolution failed because no accessible 'Add' can be called with these arguments:
    'Public Overridable Function Add(value As System.Windows.Forms.ListViewItem) As System.Windows.Forms.ListViewItem': Value of type '1-dimensional array of String' cannot be converted to 'System.Windows.Forms.ListViewItem'.
    'Public Overridable Function Add(text As String) As System.Windows.Forms.ListViewItem': Value of type '1-dimensional array of String' cannot be converted to 'String'.	C:\Documents and Settings\Sam\My Documents\Visual Studio 2008\Projects\WebRequest\WebRequest\WebRequest\frmMain.vb	48	21	WebRequest

your way???
 
Ah, b*gger! That line should have been:
VB.NET:
myListView.Items.Add(New ListViewItem(reader.ReadLine().Split(","c)))
I even read the documentation to check whether there was such an overload of Add or I had to use a ListViewItem constructor and then I went and (accidentally) ignored what I read. That code could also be expanded if that makes it clearer:
VB.NET:
Dim line As String = reader.ReadLine()
Dim fields As String() = line.Split(","c)
Dim item As New ListViewItem(fields)

myListView.Items.Add(item)

This is why you should sit down and think about WHAT your code has to achieve before worrying about HOW it's going to achieve it. Doing that, you'd never have included steps to read individual lines, combine them into a single string and then break that up into individual lines again. It would obviously be redundant.

As I said before, you should stick to one problem at a time or you will end up confusing yourself. Don't try to write ALL the code in great chunk. Divide and conquer. Write code to open a file first. Once that's done, write code to read each line of that file and display them. Once that's done, write code to break the current line up into substrings and display each one of those. Once that's done, write code to put the current fields into a ListViewItem. Don't move onto the next stage until you've finished the current stage. That way you're only solving a little problem at a time, safe in the knowledge that the previous stages all work as they should. If you're worrying about how to display data in a ListView when you don't even know how to read that data from a file, is it any wonder the problem was imposing?
 
I guess i have been worrying about the end resualt of my application before i have even finished the beginning of it. As a newbie to coding i find it amazing seeing things work. but like you said i am not taking on one problem at a time.

which is confusing the hell out of me :D
 
Back
Top