C# 程序崩溃 comboBox SelectedItem ToString

标签 c# winforms combobox

我不知道为什么我的程序会崩溃。

如果我点击“重新加载”按钮:

private void reloadBtn_Click(object sender, RoutedEventArgs e)
{
    comboFilter.Items.Clear();
    dataGridPrivatecustomers.Columns.Clear();
    dataGridPrivatecustomers.ItemsSource = null;
    load_columns_privatecustomer();
    load_values_privatecustomer();
}

所有作品。 但是,如果我为我的搜索功能选择一个过滤器并单击重新加载,它就会崩溃:

private void comboFilter_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    labelfilter.Content = "Filter: " + comboFilter.SelectedItem;
    filtervalue = comboFilter.SelectedItem.ToString();
}

这是断点:

filtervalue = comboFilter.SelectedItem.ToString();

我收到 NulLReferenceException 错误。 我尝试在 reloadBtn_Click 中创建一个 filtervalue = null; 但也不起作用。

最佳答案

comboFilter_SelectionChanged 在您从 combo 中删除项目的重新加载后以某种方式被触发,这是 clear 方法的结果。在使用之前,请确保 SelectedItemcomboFilter_SelectionChanged 中不为 null。

private void comboFilter_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if( comboFilter.SelectedItem != null)
    {
        labelfilter.Content = "Filter: " + comboFilter.SelectedItem;
        filtervalue = comboFilter.SelectedItem.ToString();
    }
}

作为附加说明,您的程序不得因未捕获程序中抛出的异常而崩溃。使用 try-catch正确处理异常。并且在它们发生之前尽量避免它们。就像我们在这里通过检查 null 所做的那样。这将防止程序崩溃。

try-catch (C# Reference) - 为什么程序会崩溃(停止执行)

When an exception is thrown, the common language runtime (CLR) looks for the catch statement that handles this exception. If the currently executing method does not contain such a catch block, the CLR looks at the method that called the current method, and so on up the call stack. If no catch block is found, then the CLR displays an unhandled exception message to the user and stops execution of the program.

关于C# 程序崩溃 comboBox SelectedItem ToString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42830040/

相关文章:

c# - Windows 8 的主题资源

C#:为什么忽略此代码?

.net - 如何取消选择 DataGridView 控件中的所有选定行?

c# - .Net Core 中的 ServiceCollectionExtensions 类有何用途?

c# - 如何将 MailMessage 对象作为 *.eml 或 *.msg 文件保存到磁盘

c# - ListView 中的换行符在 Vista/7 中有效,但在 XP 中无效

php - 在组合框中选择一个项目并用与前一个选项 php 和 mysql 相关的数据填充另一个组合框

java - 当另一个组合框的值更改时,如何更改组合框的项目?

events - ExtJS 4 - 组合框模糊事件被触发两次

c# - 从 Outlook 2010 中的选定邮件项目获取信息