我试图使一个组合框取决于在另一个组合框中选择的内容。
我已成功连接到数据库并填充了组合框,但出现以下异常System.ArgumentOutOfRangeException。异常发生在: int id = categoris [comboBoxCategory.SelectedIndex] .id;
private void comboBoxCategory_SelectedIndexChanged(object
sender,EventArgs e)
{
comboBoxMovie.Items.Clear();
**int id = categoris[comboBoxCategory.SelectedIndex].id;**
foreach (string name in GetMovieById(id))
{
this.comboBoxMovie.Items.Add(name);
}
}
谁能告诉我我做错了什么?我在下面提供了完整的代码,只是为了提供帮助。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ComboBox_Test
{
public partial class Form1 : Form
{
List<Movie> movies = new List<Movie>();
List<Category> categoris = new List<Category>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection conn = new MyConnection().GetConnection();
conn.Open();
SqlCommand cmdCate = new SqlCommand("SELECT * FROM tb_categories", conn);
SqlDataReader dr = cmdCate.ExecuteReader();
while (dr.Read())
{
comboBoxCategory.Items.Add(dr["cate_name"]);
categoris.Add(new Category(){
id = ((int)dr["cate_id"]),
cate_name = dr["cate_name"] as string
});
}
conn.Close();
conn.Open();
SqlCommand cmdMovie = new SqlCommand("SELECT * FROM tb_movies", conn);
SqlDataReader dr1 = cmdMovie.ExecuteReader();
while (dr1.Read())
{
movies.Add(new Movie()
{
id = ((int)dr1["id"]),
movie_name = dr1["movie_name"] as string,
cate_id = ((int)dr1["cate_id"])
});
}
conn.Close();
}
private string[] GetMovieById(int id)
{
return movies.Where(line=>line.cate_id==id).Select(l=> l.movie_name).ToArray();
}
private void comboBoxCategory_SelectedIndexChanged(object sender, EventArgs e)
{
comboBoxMovie.Items.Clear();
int id = categoris[comboBoxCategory.SelectedIndex].id;
foreach (string name in GetMovieById(id))
{
this.comboBoxMovie.Items.Add(name);
}
}
[Serializable]
class Category
{
public int id { get; set; }
public string cate_name { get; set; }
}
class Movie
{
public int id { get; set; }
public string movie_name { get; set; }
public int cate_id { get; set; }
}
}
}
答案 0 :(得分:0)
虽然我会承认我没有尝试构建您的代码,但如果您在问题中陈述int id = categoris[comboBoxCategory.SelectedIndex].id;
引发异常,我只能看到的解释是A)对象{ {1}}中的项目数量不及categoris
,或者B)对象comboBoxCategory
中没有实际选择的项目。如果是方案B),则comboBoxCategory
的计算结果为-1,调用comboBoxCategory.SelectedIndex
肯定会引发ArgumentOutOfRangeException。
我在B)上有我的钱,但是只有对您进行测试才能确定。如果在相关行上设置断点,是否可以确定categoris[-1]
的计算结果?如果不是-1,是否可以确定comboBoxCategory.SelectedIndex
中有多少项?