簡體   English   中英

如何在ComboBox中添加和刪除值到CheckedListBox

[英]How to add and remove values from ComboBox to CheckedListBox

我需要的:
我需要一個ComboBox和一個具有完全相同值的CheckedListBox。
我有一個按鈕來添加值和刪除值。

這是我的Add按鈕:

private void button5_Click(object sender, EventArgs e)
{
    checkedListBox1.Items.Add(comboBox1.Text);
    comboBox1.Items.Add(comboBox1.Text);
    comboBox1.Text = "";
}

和我的Delete按鈕:

private void button6_Click(object sender, EventArgs e)
{
    comboBox1.Items.Remove(comboBox1.SelectedItem);
}

我希望能夠刪除CheckedListBox中的條目而不必先選擇它,我只需要將它選擇到comboBox1

由於您要添加相同的字符串,因此可以使用IndexOf()方法獲取當前字符串在CheckedListBox中的位置,並使用RemoveAt()將其刪除。
驗證ComboBox.SelectedItem不為null。 您可以使用GetItemText()方法獲取當前選定的字符串。 如果SelectedItem為null,則返回一個空字符串。

private void button6_Click(object sender, EventArgs e)
{
    string currentItem = comboBox1.GetItemText(comboBox1.SelectedItem);
    if (!string.IsNullOrEmpty(currentItem))
    {
         checkedListBox1.Items.RemoveAt(checkedListBox1.Items.IndexOf(currentItem));
         comboBox1.Items.Remove(comboBox1.SelectedItem);
    }
}

方法2:
如果兩個控件的項目位於同一個索引,則可以使用ComboBox.SelectedIndexRemoveAt()

private void button6_Click(object sender, EventArgs e)
{
    if (comboBox1.SelectedIndex >= 0)
    {
        checkedListBox1.Items.RemoveAt(comboBox1.SelectedIndex);
        comboBox1.Items.RemoveAt(comboBox1.SelectedIndex);
    }
}

暫無
暫無

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

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