user2009692
user2009692

Reputation: 19

comboBox.SelectedValue Null error

I'm using C# VS 2010 with an Access 2010 database and I keep getting a null error (Object reference not set to an instance of an object) when I'm trying to populate a list box based on the selected DropDownList ComboBox. Example, user selects a genre of movies in the comboBox of say Westerns. The List box should then populate with titles of that Genre.

I tried getting around it by simple using

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

But then my listbox wouldn't populate with anything. I can manually set my genre to Western in the query but I'd prefer not to use that method so I can apply this to large case scenarios.

 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);
        }

    }

Upvotes: 1

Views: 302

Answers (1)

recursive
recursive

Reputation: 86134

You are adding items to comboBox1, but reading the value from comboBox. Note the lack of 1.

Upvotes: 0

Related Questions