Mobster007 Mobster007 - 1 day ago 4
C# Question

How to add text from textbox into a list

I have create a empty list which will get used when the user enters new tracks and my interface has listbox and a texbox and add and remove button.

My aim is to when i add a new item into the listbox same button use the function to add that item to a list rather them just adding to a listbox and not storing it.

trackListbox.Items.Add(newTracktextBox.Text);
List<Songs> NewSongs = newTracktextBox.Text ().ToList(); ; this is not correct


Any different ideas?

class Songs
{
private string trackName;
private int trackLength;
public Songs (string trackName, int trackLength)
{
this.trackName = trackName;
this.trackLength = trackLength;
}
}

Jim Jim
Answer

It's good practice to name the class Song instead of Songs since it will represent only one song.


With adding songs manually to the listBox

private List<Song> SongList;

public Form1()
{
    InitializeComponent();

    SongList = new List<Song>();
}

private void button1_Click(object sender, EventArgs e)    
{
    Song song = new Song(newTracktextBox.Text, 100);
    SongList.Add(song);
    listBox1.Items.Add(song); // The trackName will be shown because we are doing a override on the ToString() in the Song class
}

class Song
{
    private string trackName;
    private int trackLength;

    public Song(string trackName, int trackLength)
    {
        this.trackName = trackName;
        this.trackLength = trackLength;
    }

    public override string ToString()
    {
        return trackName;
        // Case you want to show more...
        // return trackName + ": " +  trackLength;
    }
}

With automatic binding by using a BindingList<Song>

private BindingList<Song> SongList;

public Form1()
{
    InitializeComponent();

    // Initialise a new list and bind it to the listbox
    SongList = new BindingList<Song>();
    listBox1.DataSource = SongList;
}


private void button1_Click(object sender, EventArgs e)
{
    // Create a new song and add it to the list, 
    // the listbox will automatically update accordingly
    Song song = new Song(newTracktextBox.Text, 100);
    SongList.Add(song);
}

class Song
{
    private string trackName;
    private int trackLength;

    public Song(string trackName, int trackLength)
    {
        this.trackName = trackName;
        this.trackLength = trackLength;
    }

    public override string ToString()
    {
        return trackName;
    }
}

Result

result

Comments