根据其他组合框选择填充列表框?

时间:2018-04-27 18:48:34

标签: c# sql winforms windows-forms-designer

在尝试创建音乐库存系统时,我遇到了障碍。所以我有两个组合框(cb1和cb2)和一个列表框(lb)。用户从cb1中选择是否搜索音乐专辑是流派还是艺术家。然后cb2使用我在VS表设计器中创建的SQL数据库中的数据,根据cb1选择填充艺术家列表或类型列表。最后,lb根据cb2中的选择填充数据,例如,如果cb2说" Pop"然后lb在" Pop"下填充专辑。类型。我有cb1和cb2,但我似乎无法用这些数据的组合填充lb。我手动完成了cb2,因为只有"类型"和#34;艺术家"但我有7个流派和37个艺术家,所以手动做冗余代码太多了。

到目前为止,我有一个转换GenreToAlbums和ArtistToAlbums的类:

    public List<string> GenreToAlbums(String genre)
    {
        List<string> albums = new List<string>();
        String s = "select name from Albums where genre = '" + genre + "'";

        SqlConnection c = new SqlConnection(@"Data Source=ALYSSAUSF\SQLEXPRESS;Initial Catalog=UserData;Integrated Security=True");
        SqlCommand cmd = new SqlCommand(s, c);
        c.Open();
        SqlDataReader reader = cmd.ExecuteReader();

        while (reader.Read()) 
        {
            albums.Add((string)reader["name"]);
        }

        return albums;
    }

    public List<string> ArtistToAlbums(String artist)
    {
        List<string> albums = new List<string>();
        String s = "select name from Albums where artist = '" + artist + "'";

        SqlConnection c = new SqlConnection(@"Data Source=ALYSSAUSF\SQLEXPRESS;Initial Catalog=UserData;Integrated Security=True");
        SqlCommand cmd = new SqlCommand(s, c);
        c.Open();
        SqlDataReader reader = cmd.ExecuteReader();

        while (reader.Read())
        {
            albums.Add((string)reader["name"]);
        }

        return albums;
    }

然后这是填充lb:

的cb2事件处理程序
    private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ClassItems.selectedItem == "Genre")
        {
            String selectedGenre = comboBox2.SelectedItem.ToString();

            List<string> albums = GenreToAlbums(selectedGenre);
            listBox1.DataSource = albums;
            listBox1.DisplayMember = "name";
        }
        else if (ClassItems.selectedItem == "Artist")
        {
            String selectedArtist = comboBox2.SelectedItem.ToString();

            List<string> albums = ArtistToAlbums(selectedArtist);
            listBox1.DataSource = albums;
            listBox1.DisplayMember = "name";
        }
    }

我有一个公共类ClassItems来处理一个全局变量SelectedItem,其值被改为&#34;类型&#34;或&#34;艺术家&#34;在cb1的事件处理程序类中。我的代码中的问题在哪里?

1 个答案:

答案 0 :(得分:0)

在盯着它看了几个小时后,我意识到我的错误是将cb2中的选定项目转换为字符串。它显示为DataView错误,因此我将其更改为使用GetItemText();