![](/img/trans.png)
[英]Cannot assign selected value from combobox to variable in SelectedIndexChanged event. Fill textboxes by combobox selection C# Winforms
[英]C# combobox, assign text value to variable on focus lost event?
我有一個加載了客戶 ID 的 combobox。 我有一個 function 在選擇 combobox 項目時執行一些查詢,但是如果用戶鍵入 vale,則當前功能不會做任何事情。 我正在嘗試對 combobox 使用焦點丟失事件來實現此功能,但是我當前的嘗試是在焦點丟失時返回 null 值。
我正在添加一個事件處理程序
cbxCustID.LostFocus += new EventHandler(cbxCustID_LostFocus);
function如下
private void cbxCustID_LostFocus(object sender, EventArgs e)
{
string currentText = cbxCustID.SelectedValue.ToString(); // <-- error on this line
loadName(currentText);
loadDGV(currentText);
}
即使選擇了 combobox 項目,失去對 combobox 的關注也會產生以下錯誤。 “System.NullReferenceException:'對象引用未設置為 object 的實例。'”
如果有人有任何建議或能夠在正確的方向上提供幫助,我們將不勝感激。
如果SelectedValue
是null
並且您嘗試對其調用ToString
方法,您將收到該錯誤。
你可以使用?.
null 條件運算符提前返回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);
}
}
使用Text
屬性:
private void cbxCustID_LostFocus(object sender, EventArgs e)
{
string currentText = cbxCustID.Text;
loadName(currentText);
loadDGV(currentText);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.