将项目添加到事件中的组合框时出现 InvalidOperationException
InvalidOperationException when adding items to a combobox in an event
我正在 WPF 中制作一个相当简单的 SQL 服务器 Database/Table 选择器,并且类似于 SSMS 的 "Connection Properties" 选项卡(单击“选项”按钮时),需要一个项目在将连接到服务器的组合框中,找到数据库或表的列表(取决于哪个组合框处于活动状态),并使用这些 databases/tables 填充分隔线下方的组合框。当我 运行 我的项目执行此操作时,我得到一个 InvalidOperationException 声明 'Collection was modified; enumeration operation may not execute.' 在表单的 ShowDialog 行上,而不是在表单本身内。
我已将我的事件代码包装在 Try/Catch 块中,以尝试更好地理解从何处抛出异常,但它从未在我自己的代码中捕获。异常仅在我的事件退出后抛出,在事件和 WPF 后端之间的某处,具有以下堆栈跟踪(应用程序实际启动之前的条目已被删除):
at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
at System.Collections.Generic.List`1.Enumerator.MoveNext()
at System.Windows.Controls.Primitives.Selector.SelectionChanger.CreateDeltaSelectionChange(List`1 unselectedItems, List`1 selectedItems)
at System.Windows.Controls.Primitives.Selector.SelectionChanger.End()
at System.Windows.Controls.Primitives.Selector.SelectionChanger.SelectJustThisItem(ItemInfo info, Boolean assumeInItemsCollection)
at System.Windows.Controls.ComboBox.NotifyComboBoxItemMouseUp(ComboBoxItem comboBoxItem)
at System.Windows.Controls.ComboBoxItem.OnMouseLeftButtonUp(MouseButtonEventArgs e)
at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e)
at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)
at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
at System.Windows.Input.InputManager.ProcessStagingArea()
at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Window.ShowHelper(Object booleanBox)
at System.Windows.Window.Show()
at System.Windows.Window.ShowDialog()
at VDBFImport.App.Application_Startup(Object sender, StartupEventArgs e)
例外说来源只是"mscorlib"
相关事件如下所示:
private void CbiBrowseDB_Selected(object sender, RoutedEventArgs e) {
try {
using(SqlConnection conn = new SqlConnection(GetConnectionString())) {
try {
conn.Open();
} catch(Exception ex) {
MessageBox.Show("Failed to connect to the SQL Server: " + ex.Message);
return;
}
DataTable dbs = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT [name] FROM sys.databases WHERE [name] NOT IN ('master', 'tempdb', 'model', 'msdb')", conn);
try {
adapter.Fill(dbs);
} catch(InvalidOperationException ex) {
MessageBox.Show("Failed to retrieve table list from the SQL Server: " + ex.Message);
}
try {
while(cbxDatabase.Items.Count > 2) {
cbxDatabase.Items.RemoveAt(cbxDatabase.Items.Count - 1);
}
for(int i = 0; i < dbs.Rows.Count; ++i) {
ComboBoxItem item = new ComboBoxItem();
item.Content = dbs.Rows[i].Field<string>("name");
cbxDatabase.Items.Add(item);
}
cbxDatabase.Items.Refresh();
} catch(InvalidOperationException ex) {
MessageBox.Show("Failed to update the list of databases: " + ex.Message + "\r\n" + ex.StackTrace);
}
}
} catch (Exception ex) {
MessageBox.Show("Failed.");
}
}
我希望这能正常工作,但我却得到异常 thrown.The broad "catch (Exception ex)" never executes,这向我表明这是由 WPF 在后台执行的操作引起的问题.我怀疑这可能是因为这个事件是通过在扩展组合框中选择一个选项触发的,但这种行为在 SSMS 中有效,所以我不确定我做错了什么。我发现在 foreach
循环中修改枚举时经常会出现此问题,但我没有在此事件中或此项目的其他任何地方使用过任何这些。
你正在做
while(cbxDatabase.Items.Count > 2) {
cbxDatabase.Items.RemoveAt(cbxDatabase.Items.Count - 1);
}
这里是在 while 循环中修改集合对象。而且我没有看到 cbxDatabase
在上面粘贴的代码中的任何地方被初始化。也许这是异常的原因。
您似乎处理了 ComboBoxItem
的 Selected
事件。尝试为 ComboBox
处理 SelectionChanged
事件。那么你应该没有 InvalidOperationException
.
我正在 WPF 中制作一个相当简单的 SQL 服务器 Database/Table 选择器,并且类似于 SSMS 的 "Connection Properties" 选项卡(单击“选项”按钮时),需要一个项目在将连接到服务器的组合框中,找到数据库或表的列表(取决于哪个组合框处于活动状态),并使用这些 databases/tables 填充分隔线下方的组合框。当我 运行 我的项目执行此操作时,我得到一个 InvalidOperationException 声明 'Collection was modified; enumeration operation may not execute.' 在表单的 ShowDialog 行上,而不是在表单本身内。
我已将我的事件代码包装在 Try/Catch 块中,以尝试更好地理解从何处抛出异常,但它从未在我自己的代码中捕获。异常仅在我的事件退出后抛出,在事件和 WPF 后端之间的某处,具有以下堆栈跟踪(应用程序实际启动之前的条目已被删除):
at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
at System.Collections.Generic.List`1.Enumerator.MoveNext()
at System.Windows.Controls.Primitives.Selector.SelectionChanger.CreateDeltaSelectionChange(List`1 unselectedItems, List`1 selectedItems)
at System.Windows.Controls.Primitives.Selector.SelectionChanger.End()
at System.Windows.Controls.Primitives.Selector.SelectionChanger.SelectJustThisItem(ItemInfo info, Boolean assumeInItemsCollection)
at System.Windows.Controls.ComboBox.NotifyComboBoxItemMouseUp(ComboBoxItem comboBoxItem)
at System.Windows.Controls.ComboBoxItem.OnMouseLeftButtonUp(MouseButtonEventArgs e)
at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e)
at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)
at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
at System.Windows.Input.InputManager.ProcessStagingArea()
at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Window.ShowHelper(Object booleanBox)
at System.Windows.Window.Show()
at System.Windows.Window.ShowDialog()
at VDBFImport.App.Application_Startup(Object sender, StartupEventArgs e)
例外说来源只是"mscorlib"
相关事件如下所示:
private void CbiBrowseDB_Selected(object sender, RoutedEventArgs e) {
try {
using(SqlConnection conn = new SqlConnection(GetConnectionString())) {
try {
conn.Open();
} catch(Exception ex) {
MessageBox.Show("Failed to connect to the SQL Server: " + ex.Message);
return;
}
DataTable dbs = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT [name] FROM sys.databases WHERE [name] NOT IN ('master', 'tempdb', 'model', 'msdb')", conn);
try {
adapter.Fill(dbs);
} catch(InvalidOperationException ex) {
MessageBox.Show("Failed to retrieve table list from the SQL Server: " + ex.Message);
}
try {
while(cbxDatabase.Items.Count > 2) {
cbxDatabase.Items.RemoveAt(cbxDatabase.Items.Count - 1);
}
for(int i = 0; i < dbs.Rows.Count; ++i) {
ComboBoxItem item = new ComboBoxItem();
item.Content = dbs.Rows[i].Field<string>("name");
cbxDatabase.Items.Add(item);
}
cbxDatabase.Items.Refresh();
} catch(InvalidOperationException ex) {
MessageBox.Show("Failed to update the list of databases: " + ex.Message + "\r\n" + ex.StackTrace);
}
}
} catch (Exception ex) {
MessageBox.Show("Failed.");
}
}
我希望这能正常工作,但我却得到异常 thrown.The broad "catch (Exception ex)" never executes,这向我表明这是由 WPF 在后台执行的操作引起的问题.我怀疑这可能是因为这个事件是通过在扩展组合框中选择一个选项触发的,但这种行为在 SSMS 中有效,所以我不确定我做错了什么。我发现在 foreach
循环中修改枚举时经常会出现此问题,但我没有在此事件中或此项目的其他任何地方使用过任何这些。
你正在做
while(cbxDatabase.Items.Count > 2) {
cbxDatabase.Items.RemoveAt(cbxDatabase.Items.Count - 1);
}
这里是在 while 循环中修改集合对象。而且我没有看到 cbxDatabase
在上面粘贴的代码中的任何地方被初始化。也许这是异常的原因。
您似乎处理了 ComboBoxItem
的 Selected
事件。尝试为 ComboBox
处理 SelectionChanged
事件。那么你应该没有 InvalidOperationException
.