简体   繁体   English

如何在C#中的comboBox上具有只读和可编辑项?

[英]How to have readonly and editable items on a comboBox in C#?

I am trying to add items in a ComboBox out of which 2 are ReadOnly and 1 is an editable item.. The problem I am facing,is i cant come up with a solution to edit the selected editable item.. I have create a ComboBox and added 3 items and set the dropdownStyle to DropDownList.. Can anybody help me??? 我正在尝试在ComboBox中添加项目,其中2个是ReadOnly,1个是可编辑项目。.我面临的问题是,我无法提出一种解决方案来编辑​​所选的可编辑项目。.我创建了一个ComboBox并添加了3个项目,并将dropdownStyle设置为DropDownList。有人可以帮助我吗??? Thanks 谢谢

It's not that easy. 它不是那么容易。 But possible, you can use the TextUpdate event to detect changes to the text. 但是可以使用TextUpdate事件来检测对文本的更改。 Then restore the original selection later, Control.BeginInvoke() is handy for that. 然后,稍后恢复原始选择,Control.BeginInvoke()很方便。 This sample form worked well, drop a combobox on it in the designer. 此示例表单运行良好,在设计器中放了一个组合框。 The second item is protected: 第二项受保护:

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
        comboBox1.TextUpdate += new EventHandler(comboBox1_TextUpdate);
        comboBox1.Items.Add(new Content { text = "one" });
        comboBox1.Items.Add(new Content { text = "two", ro = true });
        comboBox1.Items.Add(new Content { text = "three" });
    }

    private void comboBox1_TextUpdate(object sender, EventArgs e) {
        int index = comboBox1.SelectedIndex;
        if (index < 0) return;
        var content = (Content)comboBox1.Items[index];
        if (content.ro) this.BeginInvoke(new Action(() => {
                comboBox1.SelectedIndex = index;
                comboBox1.SelectAll();
            }));

    }

    private class Content {
        public string text;
        public bool ro;
        public override string ToString() { return text; }
    }
}

Note that you can't use DropDownList, that style doesn't allow editing. 请注意,您不能使用DropDownList,该样式不允许编辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM