我可以做什么来检测comboBox中何时为null,因为用户没有选择任何内容,并将其替换为空字符串?我用于填充comboBox DataSource。
if (comboBoxTransport.SelectedItem.ToString() == null)
comboBoxMaintenance.SelectedItem = "";
this.dataGridViewOffer.DataSource = soc.FindOffer(comboBoxCountry.SelectedItem.ToString(), comboBoxAccommodation.SelectedItem.ToString(),
comboBoxTransport.SelectedItem.ToString(), comboBoxMaintenance.SelectedItem.ToString()).ToList();
我需要它才能正确调用方法:
public List<Oferty1> FindOffer(string country, string accommodation, string transport, string maintenance) {...}
或者在这种情况下我如何以其他方式将null转换为字符串?
答案 0 :(得分:1)
您可以使用Ternary Operator
在任何需要的地方进行检查:
comboBoxTransport.SelectedItem == null ? String.Empty : comboBoxTransport.SelectedItem.ToString()
完整代码:
if (comboBoxTransport.SelectedItem == null) //ToString can not be called if property is null
comboBoxMaintenance.SelectedItem = "";
this.dataGridViewOffer.DataSource =
soc.FindOffer(
comboBoxCountry.SelectedItem == null ? String.Empty : comboBoxCountry.SelectedItem.ToString(),
comboBoxAccommodation.SelectedItem == null ? String.Empty : comboBoxAccommodation.SelectedItem.ToString(),
comboBoxTransport.SelectedItem == null ? String.Empty : comboBoxTransport.SelectedItem.ToString(),
comboBoxMaintenance.SelectedItem == null ? String.Empty : comboBoxMaintenance.SelectedItem.ToString()
).ToList();