C#组合框,在焦点丢失事件上为变量指定文本值?
我有一个已加载客户ID的组合框。我有一个函数,当选择一个组合框项目时执行一些查询,但是如果用户在vale中键入,当前的功能不会做任何事情。我正在尝试为combobox使用焦点丢失事件来实现此功能,但是当焦点丢失时,我当前的尝试返回空值 我将添加一个事件处理程序作为C#组合框,在焦点丢失事件上为变量指定文本值?,c#,combobox,C#,Combobox,我有一个已加载客户ID的组合框。我有一个函数,当选择一个组合框项目时执行一些查询,但是如果用户在vale中键入,当前的功能不会做任何事情。我正在尝试为combobox使用焦点丢失事件来实现此功能,但是当焦点丢失时,我当前的尝试返回空值 我将添加一个事件处理程序作为 cbxCustID.LostFocus += new EventHandler(cbxCustID_LostFocus); 功能如下 private void cbxCustID_LostFocus(object sender, E
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);
}
private void cbxCustID\u LostFocus(对象发送方,事件参数e)
{
string currentText=cbxCustID.SelectedValue.ToString();//如果SelectedValue
为null
并且您尝试对其调用ToString
方法,则会出现该错误
您可以使用?。
提前返回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);
}
}
如果SelectedValue
为null
并且您尝试调用ToString
方法,则会出现该错误
您可以使用?。
提前返回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);
}
}
使用文本属性:
private void cbxCustID_LostFocus(object sender, EventArgs e)
{
string currentText = cbxCustID.Text;
loadName(currentText);
loadDGV(currentText);
}
使用文本属性:
private void cbxCustID_LostFocus(object sender, EventArgs e)
{
string currentText = cbxCustID.Text;
loadName(currentText);
loadDGV(currentText);
}
我可以发誓我是allready试过的。显然不是lolI可以发誓我是allready试过的。显然不是lolI,我用了code pope的答案,但我在我的错误处理中使用了你的一些例子。谢谢,我用了code pope的答案,但我在我的错误处理中使用了你的一些例子。