Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

c# - Related comboboxes, add a third combobox

I'm trying to do a related combobox. I already have 2 comboboxes, but now I want to add a third.

I have this code for the 2nd combo box.

I'm using windows forms. The entire code: https://repl.it/@devilonline/MuddyPartialBytecode#main.cs

private string[] GetCastById(int id)
{
    return nomes.Where(line => line.movies_id== id).Select(l => l.nomes).ToArray();
}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    comboBox1.Items.Clear();
    int id = nomes[comboBox1.SelectedIndex].id;
    foreach (string name1 in GetCastById(id))
    {
        this.comboBox1.Items.Add(name1);
    }
}

print

question from:https://stackoverflow.com/questions/65598415/related-comboboxes-add-a-third-combobox

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It is obvious that you are clearing the Items of the comboBox1 then try to get the id of the selected item, which should throw an exception because no item will be selected by then:

comboBox1.Items.Clear(); // here the items are cleared
int id = nomes[comboBox1.SelectedIndex].id; // nomes[comboBox1.SelectedIndex] = -1

Based on your database, the cast table is related to the movies so each movie has a corresponding list of cast, you should then get the id of the selected movie rather than the selected nome:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    comboBox1.Items.Clear();
    int id = movies[comboBoxMovie.SelectedIndex].id; // here we used comboBoxMovie
    foreach (string name1 in GetCastById(id))
    {
        this.comboBox1.Items.Add(name1);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...