当我不 select 组合框中的项目时表单崩溃

form crashes when I dont select an item in a combobox

所以我有一个带有一些文本框和组合框的表单,在代码中我使用 textbox.text 和 combobox.selecteditem.tostring() 使用 iTextSharp 写入 pdf 文件,例如

Paragraph p = new Paragraph("\n" + "Code: " + textBox1.Text + "\n" + "Gender: " + comboBox1.SelectedItem.ToString());
doc.Add(p);

所以当我将文本框留空时,它工作正常 但是当我在没有选择项目的情况下离开组合框时,表单给出未处理的异常并崩溃

我尝试使用此代码,但没有帮助

foreach(ComboBox ncb in this.Controls.OfType<ComboBox>())
                {
                    if(ncb.SelectedItem == null)
                    {
                        ncb.SelectedItem = "";
                    }
                }

你得到一个异常,因为 comboBox1.SelectedItem 是 null,而 comboBox1.SelectedItem.ToString() 导致 NullReferenceException..

您可以通过删除 .ToString()

轻松处理它
Paragraph p = new Paragraph("\n" + "Code: " + 
                             textBox1.Text + "\n" + 
                             "Gender: " + comboBox1.SelectedItem);

如何运作的示例:

object o = null;
string s = "aaa" + o + "bbb";

s 将是 aaabbb

如果您只对组合框的字符串值感兴趣,为什么不直接使用 .Text 属性?

Paragraph p = new Paragraph($"\nCode: {textBox1.Text}\nGender: {comboBox1.Text}");