2017-10-12 69 views
-1

我想找到一種方法來在用戶沒有在下拉列表中選擇一個值時拋出一個錯誤。我嘗試了很多解決方案,這裏提供了。但是,沒有人可以work.This是我的代碼NullException在RadioButtonList中沒有選擇任何值時的錯誤

protected void Button1_Click(object sender, EventArgs e) 
    { 
     if (RadioButtonList1.SelectedItem.Value == null) 
      { 
       //Throw error to select some value before button click 
      } 

     if (RadioButtonList1.SelectedItem.Value == 'male') 
      { 
       //Step1 
      } 
     if (RadioButtonList1.SelectedItem.Value == 'female') 
      { 
       //Step2 
      } 
    } 

試圖與

if (RadioButtonList1.SelectedIndex == -1) 

更換,但同樣沒有工作。有任何想法嗎?從評論

+1

如果沒有選擇,什麼*是* SelectedIndex,如果不是'-1'?當你調試時,實際價值是多少? – David

+1

「RadioButtonList1.SelectedItem.Value == null」的作品? SelectedItem應該爲空。 –

+0

執行代碼僅在選擇單選按鈕時執行,當用戶單擊時沒有選擇時出現錯誤 - 對象引用未設置爲對象的實例...並且沒有「RadioButtonList1.SelectedItem.Value」== null不工作 – rakesh

回答

0

這將是更容易爲你如果選擇的項目被放入變量調試:

var selectedItem = RadioButtonList1.SelectedItem; 
if (selectedItem == null) 
{ 
    throw new Exception("Please select"); 
} 
else if (selectedItem.Value == "male") 
{ 
    // step 1 
} 

單選按鈕是具體的。如果沒有選擇任何內容,則不存在selectedItem,因此不存在不存在的對象的值。

編輯:將調試點放在第一行,var selectedItem = ..所以你將在懸停知道它有什麼確切的價值。

編輯2:總是檢查你的對象是否不爲空。您在評論中的錯誤是由於您在實際對象不存在時立即嘗試訪問對象屬性所致。

1

報價:

(勒凱什)僅當選擇了單選按鈕的實際工作的代碼執行時,當用戶點擊沒有選擇我的錯誤 - 不設置爲一個對象的實例對象引用...和NO 「RadioButtonList1.SelectedItem.Value」 == NULL不起作用

那是你的方式!錯誤的原因是:RadioButtonList1.SelectedItem爲空。所以沒有的值。所以說:只要檢查

if (RadioButtonList1.SelectedItem == null) {...} 

編輯澄清討論:

if (RadioButtonList1.SelectedItem == null) 
{ 
    //Throw error to select some value before button click 
} 
else if (RadioButtonList1.SelectedItem.Value == "...") 
{ 
    .... 
} 
+0

我試過了。但它跳過'RadioButtonList1.SelectedItem == null'移動到具有相同錯誤的下一個條件 - 請參見圖片:http://ibb.co/itapFb – rakesh

+1

它不會跳過!它執行。但它也會執行發生錯誤的行。嘗試塊中的「返回」或「else if」。 –

+0

謝謝!它執行了多重條件。我必須在一次執行後結束該塊。再次感謝。 – rakesh

相關問題