2013-01-25 22 views
2

我正在使用C#VS 2010與Access 2010數據庫,並且當我嘗試填充基於列表框的對象時,我一直收到空錯誤(對象引用未設置爲對象實例)在選定的DropDownList組合框上。例如,用戶在說西部片的組合框中選擇一個電影流派。列表框然後應該填充該流派的標題。comboBox.SelectedValue空錯誤

我嘗試使用

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

避過它通過簡單的但是後來我的列表框將不與任何填充。我可以在查詢中手動將我的類型設置爲Western,但我不希望使用該方法,因此我可以將其應用於大型情況。

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 [email protected]", 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); 
     } 

    } 

回答

0

您將項目添加到comboBox1,但comboBox讀取值。請注意缺少1