[英]ComboBox.SelectionLength = 0 throws InvalidArgument Exception
對於ComboBox,當我將SelectionLength設置為0時,出現錯誤:
InvalidArgument=Value of '-1470366488' is not valid for 'start'.
Parameter name: start
Stack Trace:
at System.Windows.Forms.ComboBox.Select(Int32 start, Int32 length)
at System.Windows.Forms.ComboBox.set_SelectionLength(Int32 value)
at MyCompany.Odin.WebClient.STComplexView.loadViewFormats()
這不是在Clear()
,也不是綁定控件。
這段代碼中(不太有趣)的事情:
//Adding Items to the combo box (6 in total)
// ...
viewFormatComboBox.Items.Add(appResMgr.GetString("STR_6X2_HEXAXIAL"));
viewFormatComboBox.SelectedIndex = 2;
viewFormatComboBox.SelectionLength = 0; //<<<< The exception is thrown here
在我們的代碼中沒有任何地方指定SelectionStart,但是當我到達上面包含的代碼時,它已經獲得了-1470366488的值。 我認為這是當ComboBox做一個
ComboBox.Select(Int32 start, Int32 length)
調用,通過設置SelectionLength觸發。 我假設SelectionStart用於開始參數和中提琴,上面顯示了InvalidExceptionArgument。
這是在調試代碼中。 樣式是DropDownStyle
,其他所有東西看起來都沒什么變化,但是在調試器中,我看到SelectionStart
屬性是-1470366488。
這段代碼已經存在了兩年,今天,我在測試調試版本時第一次遇到此異常。 我正在選擇要用SelectedIndex = 2行顯示的項目,然后在設置SelectionLength時出現異常有任何解釋嗎?
從異常和調用堆棧看來,最簡單的解決方案是插入:
viewFormatComboBox.SelectionStart = 0;
之前
viewFormatComboBox.SelectionLength = 0;
以確保它具有有效值。
對於DropDownList的組合框樣式,組合框控件實際上沒有“文本”框實體。 因此,如上所述,設置該對象的SelectionStart或SelectionLength會產生不可預測的結果。 如其他文章中提到的( 由於在“ DropDownList”模式下使用.Net ComboBox屬性SelectionStart&SelectionLength引起的怪異行為 , http://social.msdn.microsoft.com/forums/en-us/csharpgeneral/thread/80B562C9-981E- 48E6-8737-727CE5553CBB ),也建議不要使用這些屬性,我明白了為什么。 但是測試該樣式而不設置“開始”值可以解決我們的問題。
如果不是Me.DropDownStyle.Equals(Windows.Forms.ComboBoxStyle.DropDownList),則Me.SelectionStart = Me.Text.Length結束
希望這對以后的人有所幫助...
這是對什么而不是原因的解釋。
SelectionLength的設置程序調用:
this.Select(this.SelectionStart, value);
第一行檢查arg的有效性
if (start < 0)
{
throw new ArgumentOutOfRangeException("start", System.Windows.Forms.SR.GetString("InvalidArgument", (object) "start", (object) start.ToString((IFormatProvider) CultureInfo.CurrentCulture)));
}
如您所指出的,您的SelectionStart值為-1470366488。 問題是為什么? SelectionStart調用的獲取器:
int[] wParam = new int[1];
System.Windows.Forms.UnsafeNativeMethods.SendMessage(new HandleRef((object) this, this.Handle), 320, wParam, (int[]) null);
return wParam[0];
消息320(0x140)為CB_GETEDITSEL。 根據docs ,應該返回:
在組合框的編輯控件中獲取當前所選內容的開始和結束字符位置。
顯然不是。 返回-1470366488。 為什么? 誰知道。 我猜想CB_GETEDITSEL返回一個錯誤,該錯誤未檢查並且wParam [0]未定義,並且框架只是盲目地使用它。
可能在設置SelectionLength之前顯式設置SelectionStart(發送CB_SETEDITSEL)將使發生這種情況的可能性降到最低。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.