我在我的项目中使用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