列表无法清除!c#

本文关键字:清除 列表 | 更新日期: 2023-09-27 18:06:27

//selects the movie option, this will populate the movie lists (titles only)
    private void btnMovies_Click(object sender, EventArgs e)
    {
        int size = 0;
        string titles = null;
        byte[] dataSend = new byte[1024];
        byte[] dataReceive = new byte[1024];
        string[] split = null;
        movieList.Items.Clear();
        movietitles.Clear();
        try
        {
            Array.Clear(dataSend, 0, dataSend.Length);
            dataSend = Encoding.ASCII.GetBytes("movies");
            socket.Send(dataSend);
            size = socket.Receive(dataReceive);//receive movie titles
            titles = Encoding.ASCII.GetString(dataReceive, 0, size);
            char[] separators = { ';' };
            split = titles.Split(separators);
            for (int i =0;i<split.Count();i++)
            {
                movietitles.Add(split[i]);
            }
            foreach (string smovie in movietitles)
            {
                movieList.Items.Add(smovie);
            }

        }
        catch (SocketException ex)
        {
            lblError.Text = "Unable to connect to server";
            lblError.Text += ex;
        }
        pnlMovies.Visible = true;

    }

所以这里发生的事情是,我用movietitles列表中的电影标题填充movieList (listbox)。然而,每次我按下按钮电影再次填充它没有清除前一个,即使我清除了它。我打印出了电影标题的。count,它每次都增加一倍,所以这肯定是问题所在。

我已经。clear()它,所以我不确定我还能做什么。我重置了所有的变量,但没有工作。谢谢!

列表无法清除!c#

我认为如果将ListBox绑定到数据源可能会更好。比如:

//populate your List with your movie titles
private List<String> movieTitles = new List<string>() { "movie1", "movie2", "movie3" };
//Then bind the datasource
movieList.ItemSource = movieTitles;