2012-11-22 28 views
0

我有一個將項目添加到檢查列表框的按鈕。使用按鈕編輯並刪除檢查列表框中的項目

private void btnDelivery_Click(object sender, EventArgs e) 
{ 
    deliveryForm.deliverytrips = new DeliveryTrips(); 
    deliveryForm.ShowDialog(); 
    if (deliveryForm.deliverytrips != null) 
    { 
     DeliveryTrips newApp = deliveryForm.deliverytrips; 
     theDelivery.addDeliveryTrip(newApp); 
    } 
    updateList(); 
} 

private void updateList() 
{ 
    clbSummary.Items.Clear(); 
    List<String> listOfDelivery = theDelivery.listDeliveryTrips(); 
    clbSummary.Items.AddRange(listOfDelivery.ToArray()); 
} 

使用按鈕我該如何編輯,我已添加到清單框中或將它從檢查列表框中刪除?

我剛纔這對於編輯項目

 int index = clbSummary.SelectedIndex; 



     DeliveryTrips selected = theDelivery.getDeliveryTrips(index); 


     deliveryForm.deliverytrips = selected; 



     deliveryForm.ShowDialog(); 


     updateList(); 

但是,如果選擇不檢查,同時與刪除按鈕只能編輯的項目,如果選擇不檢查,只刪除項目。

謝謝

+0

用你的方法的問題是,您有效地有兩種方法來指示選擇一個'CheckedListBox':選擇和檢查。我會傾向於將控件更改爲常規的「ListBox」,或者決定一種檢測選擇的方式並堅持。 –

+0

CheckedListBox有一個CheckedItems枚舉。 – LarsTech

+0

SidHolland寧願保留[tag:CheckedListBox],因爲它是我將添加到[tag:CheckedListBox]後面的所有項目的總結,稍後我將把某些項目移動到[tag:ListBox],因此它應該希望更容易移動一些檢查項目到不同的[標籤:列表框],而不是將一個選定的項目移動到不同的[標籤:列表框] @LarsTech我試過使用CheckedItems,但我得到一個req行下它 – Michael

回答

2

刪除是容易的部分。如果您的列表支持選擇單個項目(SelectionModeOne),你可以這樣做

private void DeleteButton_Click(object sender, EventArgs 
{ 
    clbSummary.Items.RemoveAt(clbSummary.SelectedIndex); 
} 

現在,如果你支持多重選擇(SelectionModeMultiSimple/MultiExtended - 工程標準列表,而不是CheckboxLists),下面的代碼將刪除整個選擇

private void DeleteButton_Click(object sender, EventArgs e) 
{ 
    for(int i = clbSummary.SelectedIndices.Count - 1; i >= 0; --i) 
    { 
     clbSummary.Items.RemoveAt(clbSummary.SelectedIndices[i]); 
    } 
} 

這裏,是顛倒順序很重要,否則在項目拆除將改變你的clbSummary的內容和更多的刪除項目,該偏移量將更大。

如果你想刪除選中的項目,這是同樣的事情,但是你用CheckedIndices

private void DeleteButton_Click(object sender, EventArgs e) 
{ 
    for (int i = clbSummary.CheckedIndices.Count - 1; i >= 0; --i) 
    { 
     clbSummary.Items.RemoveAt(clbSummary.CheckedIndices[i]); 
    } 
} 

要編輯,我建議創建一個表單編輯您的項目的內容,或者如果它只是一個字符串,也許一個簡單的輸入對話框就足夠了(我真的簡化了它使用參考Microsoft.VisualBasic使用InputBox)。通常你的項目可能對應不是字符串更復雜的對象,以便適當Editor可能是必要的(專門用來編輯項目表單)

private void EditButton_Click(object sender, EventArgs e) 
{ 
    string content = clbSummary.SelectedItem.ToString(); 
    string newValue = Interaction.InputBox("Provide new value", "New Value", content, -1, -1); 
    int selectedIndex = clbSummary.SelectedIndex; 
    clbSummary.Items.RemoveAt(selectedIndex); 
    clbSummary.Items.Insert(selectedIndex, newValue); 
} 
+0

真棒謝謝 我已經有一個論壇使用,讓我添加和編輯項目,然後更新它們。 現在只剩下一個問題,它的工作如果有一個項目選擇,我只需要改變它,而不是選定的項目,它對檢查項目 我試圖使用'Int index = clbSummary.CheckedItems;'但是我只是在代碼下面出現一條紅線,或許我錯過了某些東西? – Michael

+0

'CheckedItems'是一個'Collection',它包含很多項目。你將不得不從這個'Collection'中選擇一個,所以爲了編輯,我建議使用'SelectionMode''One',並編輯'SelectedItem' – emartel

相關問題