Search code examples
vb.netlistboxruntimebasic

Create list box in runtime and change its color via menu in runtime


I need to write this small program in visual basic, but i face a problem which is i can't change the color or add list form text file during runtime.

this is picture of what i wont to do

http://i62.tinypic.com/30tghh0.png

And this is the code i wrote so far,,

    Public Class Form1

    Private Sub NewToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NewToolStripMenuItem.Click
        Dim listBox1 As New System.Windows.Forms.ListBox
        listBox1.Text = "New List"
        listBox1.Location = New Point(25, 25)
        listBox1.Size = New Size(380, 280)
        Me.Controls.Add(listBox1)
        OpenToolStripMenuItem.Enabled = True
        SaveToolStripMenuItem.Enabled = True
        SaveAsToolStripMenuItem.Enabled = True
        CloseToolStripMenuItem.Enabled = True
        EditToolStripMenuItem.Enabled = True

    End Sub

    Private Sub ExirToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExirToolStripMenuItem.Click
        End

    End Sub


    Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click

        If (OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK) Then
            Dim myfile As String = OpenFileDialog1.FileName
            Dim allLines As String() = File.ReadAllLines(myfile)
            For Each line As String In allLines
                ListBox1.Items.Add(line)
            Next
        End If
    End Sub
End Class

The problem as you see is in OpenToolStripMenuItem sub with line ListBox1.Items.Add(line)

is there is no listbox1 because is not created yet.the same with color, save and the rest.

so, please help me to solve it.


Solution

  • Move the declaration of ListBox1 out to the Class level:

    Public Class Form1
    
        Private ListBox1 As System.Windows.Forms.ListBox
    
        Private Sub NewToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NewToolStripMenuItem.Click
            ListBox1 = New System.Windows.Forms.ListBox
            ...
        End Sub
    
        ...
    
    End Class
    

    *But why create it at run-time like this? You could add it at design-time and set the Visible() property to False. When the New button is clicked, you change Visible() to True. Unless you need a new ListBox to be created each time so you have more than one? If so, how will they be laid out?...