【问题标题】:How to add and remove values from ComboBox to CheckedListBox如何将值从 ComboBox 添加和删除到 CheckedListBox
【发布时间】:2019-05-03 00:52:00
【问题描述】:

我需要什么:
我需要一个具有完全相同值的 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 中。

【问题讨论】:

    标签: c# winforms checkbox combobox


    【解决方案1】:

    由于您要添加相同的字符串,因此您可以使用 IndexOf() 方法获取 CheckedListBox 中当前字符串所在的索引,并使用 RemoveAt() 将其删除。
    验证 ComboBox.SelectedItem 不为空。您可以使用GetItemText() 方法获取当前选中的字符串。如果SelectedItem 为空,则返回一个空字符串。

    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);
        }
    }
    

    方法二:
    如果两个控件的 Items 位于同一索引,则可以改为使用 ComboBox.SelectedIndex 到 RemoveAt() 两者:

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

    【讨论】:

    • 现在,我怎样才能使它也删除我的 dataGridView 中的一行? comboBox、checkedListBox 和 dataGridView 都将具有完全相同的行。仅通过选择组合框中的项目。
    • 不同的话题,不同的问题。您必须描述 DGV 的填充方式(使用什么方法,是否是数据绑定等)。您必须提出另一个问题,解释实际情况。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多