【问题标题】:C# combobox, assign text value to variable on focus lost event?C#组合框,将文本值分配给焦点丢失事件的变量?
【发布时间】:2020-05-08 18:12:54
【问题描述】:

我有一个加载了客户 ID 的组合框。我有一个函数可以在选择组合框项时执行一些查询,但是如果用户键入 vale,则当前功能不会执行任何操作。我正在尝试使用组合框的焦点丢失事件来实现此功能,但是我当前的尝试在焦点丢失时返回空值。

我正在添加一个事件处理程序

cbxCustID.LostFocus += new EventHandler(cbxCustID_LostFocus);

函数如下

private void cbxCustID_LostFocus(object sender, EventArgs e)
{
    string currentText = cbxCustID.SelectedValue.ToString();  //  <-- error on this line
    loadName(currentText);
    loadDGV(currentText);
}

即使选择了组合框项目,失去对组合框的关注也会产生以下错误。 "System.NullReferenceException: '对象引用未设置为对象的实例。'"

如果有人有任何建议或能够提供正确方向的推动,我们将不胜感激。

【问题讨论】:

    标签: c# combobox


    【解决方案1】:

    使用Text 属性:

    private void cbxCustID_LostFocus(object sender, EventArgs e)
    {
        string currentText = cbxCustID.Text;  
        loadName(currentText);
        loadDGV(currentText);
    }
    

    【讨论】:

    • 我可以发誓我已经尝试过了。显然不是大声笑
    【解决方案2】:

    如果SelectedValuenull 并且您尝试对其调用ToString 方法,您将收到该错误。

    您可以使用?. null conditional operator 提前返回null 并避免异常:

    string currentText = cbxCustID.SelectedValue?.ToString();
    

    现在,根据您的需要,在调用其他方法之前,您可能仍需要检查 currentText 是否为 null

    private void cbxCustID_LostFocus(object sender, EventArgs e)
    {
        string currentText = cbxCustID.SelectedValue?.ToString();
    
        if (currentText != null)
        {
            loadName(currentText);
            loadDGV(currentText);
        }
    }
    

    【讨论】:

    • 谢谢,我使用了代码教皇的回答,但我在错误处理中确实使用了你的一些示例。
    猜你喜欢
    • 1970-01-01
    • 2016-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-03
    相关资源
    最近更新 更多