【问题标题】:comboBox.SelectedValue Null errorcomboBox.SelectedValue 空错误
【发布时间】:2013-01-09 00:39:59
【问题描述】:

我将 C# VS 2010 与 Access 2010 数据库一起使用,当我尝试基于选定的 DropDownList ComboBox 填充列表框时,我不断收到 null 错误(对象引用未设置为对象的实例) .例如,用户在说西部片的组合框中选择电影类型。然后,列表框应填充该类型的标题。

我尝试通过简单的使用来解决它

ComboBox c = New ComboBox();
c = comboBox1;

但是我的列表框不会填充任何内容。我可以在查询中手动将我的流派设置为西方,但我不想使用该方法,因此我可以将其应用于大型案例场景。

 public partial class Form1 : Form
{
    OleDbConnection cn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data source = c:\\users\\Nick\\Desktop\\DatabaseTest.accdb");
    public Form1()
    {
        InitializeComponent();
    }
    private void Form1_Shown(object sender, EventArgs e)
    {
        try
        {
            cn.Open();
        }
        catch (ObjectDisposedException ex)
        {
            MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            Application.Exit();
        }
        OleDbCommand cm = new OleDbCommand("SELECT Genre FROM Genre", cn);
        try
        {
            OleDbDataReader dr = cm.ExecuteReader();

            while (dr.Read())
            {
                comboBox1.Items.Add(dr["Genre"]);

            }
            dr.Close();
            dr.Dispose();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    //private void button1_Click(object sender, EventArgs e)
    //{

    //}

    private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
    {
        OleDbCommand cf = new OleDbCommand("SELECT Title FROM Movies WHERE mGenreID=@Genre", cn);
        cf.Parameters.Add("@Genre", comboBox.SelectedValue.ToString());

        try
        {
            OleDbDataReader dr = cf.ExecuteReader();

            while (dr.Read())
            {
                listBox1.Items.Add(dr["Title"]);
            }
            dr.Close();
            dr.Dispose();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

    }

【问题讨论】:

    标签: combobox null selecteditem


    【解决方案1】:

    您正在向comboBox1 添加项目,但从comboBox 读取值。请注意缺少1

    【讨论】:

      猜你喜欢
      • 2012-10-04
      • 2019-07-22
      • 2013-09-14
      • 2012-08-23
      • 2012-03-09
      • 1970-01-01
      • 2010-09-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多