ComboBox Event Triggered for the Change

Suppose I have a C# .NET windows forms application with a ComboBox that selects string values and also accepts the entry of new values.

What is the most efficient way to trigger a event handling method when either

  • a preexisting value of the combo box is selected, or
  • a newly entered value is typed/entered into the combo box?
  • I've tried options like the SelectedIndexChanged event, but I can't seem to get things to trigger when there are a newly entered values. I would assume this is a fairly simple thing to pull of, but I'm not sure.

    I could trap for the Enter key, but that seems half-broken assumption that that is what signifies an update.


    I'd use the ComboBox_SelectedIndexChanged for changes to the selected item.

    I'd also trap the ComboBox_Leave event to check if the item is new (doesn't exist in the list). This will cater for Enter, Tab keys and mouse clicks that switch focus from the ComboBox.

    Also check out "filterable DataGridViews", on the web there's a few msdn and codeproject articles that will help.


    Without knowing what your full requirements are, I question if a combo box is the appropriate control for this. My first observation would be that allowing users to enter new combo box items on the fly is a possible opening of a Pandora's Box. I can easily see duplication of items from a simple misspelling among other user antics that are bound to happen. This is going to be a headache in the future.

    As @Jeremy Thompson suggest, wiring up the combo boxes “Leave” event may help, You could use the ComboBox.Text property to get the new text the user typed in, then check if it already exist and is not empty or null, then simply add it to the combo boxes items list. This should work, but I am guessing there may be a better way to achieve your goal. What would the user be typing into the combo box?

    private void comboBox1_Leave(object sender, EventArgs e) {
      string currentSelection = comboBox1.Text;
      if (currentSelection != null && currentSelection != "" && !comboBox1.Items.Contains(currentSelection)) {
        comboBox1.Items.Add(currentSelection);
      }
    }
    
    链接地址: http://www.djcxy.com/p/68602.html

    上一篇: 用于矢量数据的限制玻尔兹曼机的替代方案(而不是二进制)

    下一篇: 组合框事件触发了更改