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

时间:2016-12-01 12:52:25

标签: c# list arraylist textbox listboxitem

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

我的目标是当我在列表框中添加一个新项目时,使用该功能将该项目添加到列表中,而不是只添加到列表框而不是存储它。

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

3 个答案:

答案 0 :(得分:3)

试试这个

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

List<Songs> NewSongs = new List<Songs>();
NewSongs.Add(objSong);

答案 1 :(得分:0)

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()方法可能是还原的。

希望我帮助

答案 2 :(得分:0)

最好将课程命名为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; } }

进行自动绑定
{elseif in_array($feature.feature_type, ["ProductFeatures::TEXT_SELECTBOX"|enum, "ProductFeatures::EXTENDED"|enum, "ProductFeatures::NUMBER_SELECTBOX"|enum])}
                {foreach from=$feature.variants item="var"}
                    {if $var.selected}{$var.variant}, {/if}
                {/foreach}

<强>结果

result