簡體   English   中英

清除(刪除)組合框項目將引發異常

[英]Clear(remove) combobox items throws exception

我有組合框,當單擊按鈕時,該組合框已正確填充了某些字段ID。

private void Button_Click(object sender, RoutedEventArgs e)
{         
    results.Items.Add(ID);          
}

現在我想當我更改一些值以刪除以前的值(或在組合框中有多個值的情況下刪除值)但我總是會遇到異常(如果組合框中已經選擇了某些值),我試圖在該方法上添加該方法最重要的是:

results.Items.Clear();

我嘗試了這個:

for (int i = 0; i < results.Items.Count; i++)
{
    results.Items.RemoveAt(i);
    i--;
}

但總是會出現異常:

System.ArgumentException:值不在預期范圍內。 在MS.Internal.XcpImports.MethodEx(IntPtr ptr,字符串名稱,CValue [] cvData)在MS.Internal.XcpImports.MethodPack(IntPtr objectPtr,字符串methodName,Object [] rawData)在MS.Internal.XcpImports.Collection_Add [T ](在System.Windows.PresentationFrameworkCollection'1.AddImpl(對象值)在System.Windows.Controls.ItemCollection.AddImpl(對象值)在System.Windows.Controls.ItemCollection.AddInternal(Object System.Windows.PresentationFrameworkCollection'1.Add(T值)在SXPCreateIncident3.SilverlightControl1.results_SelectionChanged(Object sender,SelectionChangedEventArgs e)在System.Windows.Controls.Primitives.Selector.OnSelectionChanged(SelectionChangedEventArg)

如果我沒有“清除(刪除)”這一部分,則組合框的每個按鈕“單擊”上都有更多元素,但是單擊按鈕時我需要清除以前的內容。

您是否嘗試取消選擇所有項目然后再刪除:

results.SelectedIndex = -1;
results.Items.Clear();

萬一Clear仍然會造成一些麻煩,您的第二種方法不應該是:

for (int i = results.Items.Count - 1; i >= 0; i--)
{
    results.Items.RemoveAt(i);
}

我不完全確定result.Items如何綁定到您的Combobox但是您可以嘗試用新的項目替換不需要的項目:

private void Button_Click(object sender, RoutedEventArgs e)
{
    // itemToRemove should already be set    
    var index = result.Items.IndexOf(itemToRemove);     
    results.Items[index ] = ID;          
}

要刪除多個項目,請不要使用迭代器。 使用迭代器時從集合中刪除內容會使迭代器混亂。 但是,您可以這樣做:

private void Button_Click(object sender, RoutedEventArgs e)
{
    for(var i = 0; i < result.Items.Count; i++)
    {
        // itemsToRemove should be populated with the IDs you want to remove.
        if(itemsToRemove.Contains(result.Items[i])
        {
            result.RemoveAt(i);
        }
    }
    result.Items.Add(ID);
}

因為每次對表達式i < result.Items.Count進行求值,並且刪除ID后, Count都比前一個Count小1,所以此循環不會陷入混亂。

編輯要清除組合框並用新項目填充它,您必須為組合框提供新的ItemsSource

private void Button_Click(object sender, RoutedEventArgs e)
{
    results.ItemsSource = null;
    results.ItemsSource = new List<SomeType>(); // replace SomeType with the type of ID.
    results.Items.Add(ID);          
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM