我在我的項目中使用WinForms和MySQL。WinForm Combobox上的空錯誤
我的表結構...
在我的項目,我有三個組合框和了一個TextBox。在「選項」組合框包含三個值:
- 市
- 國家
- 國家
當我選擇的城市,州和國家組合框必須選擇。
當我選擇的國家,國家組合框必須選擇。
當我選擇的國家,就沒有必要選擇國家和國家組合框。
我試圖用這個代碼中插入這樣的數據:
MySqlConnection connection = new MySqlConnection("server=192.168.1.100;User Id=mcubic;[email protected]$;database=mcs;Persist Security Info=True");
MySqlCommand command = new MySqlCommand("Insert into test (name1,option1,state,country) VALUES ('" + textBox1.Text + "','" + cmbo_Options.SelectedItem.ToString() + "','" + cmbo_state.SelectedItem.ToString() + "','" + cmbo_country.SelectedItem.ToString() + "')", connection);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
當選擇了所有組合框,此代碼工作正常。但是當State ComboBox沒有被選中時,它會拋出一個NullReferenceException異常。
未將對象引用設置爲對象的實例。空錯誤。
所以我更新了我的代碼:
string country = cmbo_country.SelectedItem.ToString();
string state = cmbo_state.SelectedItem.ToString();
MySqlConnection connection = new MySqlConnection("server=192.168.1.100;User Id=mcubic;[email protected]$;database=mcs;Persist Security Info=True");
MySqlCommand command = new MySqlCommand("Insert into test (name1,option1,state,country) VALUES ('" + textBox1.Text + "','" + cmbo_Options.SelectedItem.ToString() + "','" + state + "','" + country + "')", connection);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
我無法逃避這個錯誤。我的代碼應該如何用於這個項目?
調試你的代碼,找到引發異常的確切行。 ... SelectedItem可以爲null。 – Devart 2012-01-27 07:48:58
cmbo_country.SelectedItem.ToString();給出錯誤。如何解決這個問題? – Sagotharan 2012-01-27 07:52:06
因此,然後ToString()拋出錯誤,因爲組合框是空的或沒有選定的項目。你應該處理這種情況,例如 - 寫'如果'的情況。 – Devart 2012-01-27 07:58:22