ComboBox.SelectionLength = 0抛出InvalidArgument异常

时间:2012-01-31 20:19:52

标签: c# .net winforms combobox

对于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用于start参数和viola,我们在上面显示了InvalidExceptionArgument。

这是在调试代码中。样式为DropDownStyle,其他一切看起来都不起眼,但在调试器中我看到SelectionStart属性为-1470366488。

这段代码已经存在了几年,今天我在测试调试版本时第一次遇到这个例外。我选择了我想用SelectedIndex = 2行显示的项目,然后在设置SelectionLength时得到异常 有什么解释吗?

3 个答案:

答案 0 :(得分:2)

从异常和调用堆栈看,最简单的解决方案是插入:

viewFormatComboBox.SelectionStart = 0;

viewFormatComboBox.SelectionLength = 0;

确保它具有有效值。

答案 1 :(得分:1)

这是对什么而不是为什么的解释。

SelectionLength的setter调用:

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调用的getter:

int[] wParam = new int[1];
System.Windows.Forms.UnsafeNativeMethods.SendMessage(new HandleRef((object) this, this.Handle), 320, wParam, (int[]) null);
return wParam[0];

Msg 320(0x140)是CB_GETEDITSEL。根据{{​​3}},应返回:

  

获取当前的起始和结束字符位置   在组合框的编辑控件中进行选择。

显然不是。它正在返回-1470366488。为什么?谁知道。我猜想CB_GETEDITSEL会返回一个错误,这个错误没有被检查过,而且wParam [0]是未定义的,框架只是盲目地使用它。

在设置SelectionLength之前,也许明确设置SelectionStart(发送CB_SETEDITSEL)将最大限度地减少它发生的可能性。

答案 2 :(得分:1)

对于DropDownList的组合框样式,组合框控件实际上没有“文本”框实体。因此,如上所述,设置该对象的SelectionStart或SelectionLength具有不可预测的结果。正如其他帖子(Weird behavior caused by using .Net ComboBox properties SelectionStart & SelectionLength in "DropDownList" modehttp://social.msdn.microsoft.com/forums/en-us/csharpgeneral/thread/80B562C9-981E-48E6-8737-727CE5553CBB)中所提到的,也建议不要使用这些属性,我明白为什么。但是测试该样式而没有设置Start值可以解决我们的问题。

如果不是Me.DropDownStyle.Equals(Windows.Forms.ComboBoxStyle.DropDownList)那么     Me.SelectionStart = Me.Text.Length 结束如果

希望这有助于将来......

相关问题