如何将文本框中的文本添加到列表中

How to add text from textbox into a list

我创建了一个空列表,当用户输入新曲目并且我的界面有列表框和文本框以及添加和删除按钮时将被使用。

我的目标是当我将新项目添加到列表框中时,使用相同的按钮使用该功能将该项目添加到列表中,而不是它们只是添加到列表框中而不是存储它。

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

有什么不同的想法吗?

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

您的 newTracktextBox 变量不是 Song 类型的对象。

您应该使用 newTracktextBox 中的文本创建一个类型为 Song 的新对象,并将新对象添加到列表中

试试这个

Songs objSong = new Songs(newTracktextBox.Text,0); // define your length instead of 0

List<Songs> NewSongs = new List<Songs>();
NewSongs.Add(objSong);
public class Songs{
    String TrackName;
    int TrackLength;
    public Songs(string trackName, int trackLength){
       this.TrackName = trackName;
       this.TrackLength = trackLength;
   }
   //methods
}

制作一个歌曲列表

List<Songs> NewSongs = new List<Songs>();

通过

将新歌添加到列表
int tracklength = 50; // set the tracklength where you need
NewSongs.Add(new Songs(TextBox.Text.ToString(),tracklegnth));

请注意,ToString() 方法可能是多余的。

希望我能帮到你

最好将 class 命名为 Song 而不是 Songs,因为它将仅代表 歌曲。


手动添加歌曲到 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;
    }
}

使用 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;
    }
}

结果