ComboBox.Text = null string instead of actual displayed string

Disclaimer - I've only been using C# for about a week now, so hopefully this isn't a n00b question. I did look around, but was unable to find a solution that worked, including the results from this thread.

I have a combobox on a Windows form. The combobox's data is populated from an Access database. The relevant properties that I have set are - AutoCompleteMode = Append; AutoCompleteSource = ListItems; DropDownStyle = DropDown. The users must be able to type in the combobox and it autocomplete, so the DropDownStyle of DropDownList will not work. Instead of using the default drop down arrows I have a dynamic PictureBox replacing it. Clicking on the PictureBox or triggering the Enter event will set the DropDowned property of the combobox to true.

As it currently is, users can select items just fine or type in items and press enter or type in items and leave the field, etc.... During all of those different types of interactions I am able to determine what the correct value in the combobox is. I have certain triggers to ensure that the SelectedValue and the displayed Text are always in sync.

I am able to get the correct value under every possible interaction, that I could think of, except for one. If the user starts to type a string (with the DropDowned property = true) and hits the right arrow key to have the string autocomplete, the string in the combobox is always a null string.

Visual:

Selected_ Text

The bolded text in the above string is the highlighted text in the combobox. If the user then hits the right arrow key to make the text in the combobox look like

Selected_Text

(Note that DropDowned is still true at this point) the ComboBox.Text value is always "".

Here is the code for one of the ComboBoxes' DropDownClosed event, which is the first thing that is triggered once the user presses enter.

private void cmbxYear_DropDownClosed(object sender, EventArgs e)
    {
        try
        {
            if (!cmbxYear.Text.Equals(cmbxYear.SelectedValue.ToString()))
            {
                if (!bUpdated & !bErrorFound)
                {
                    validateData(cmbxYear, clrYear, false, imgFilter1, imgNoFilter1);
                    updateTable();
                }
            }
            imgFilter1.Visible = false;
            imgNoFilter1.Visible = true;
        }
        catch
        {
            imgNoFilter1.Visible = false;
            imgFilter1.Visible = true;
        }
    }

I also just discovered that the ComboBox.Text is always a null string when the DropDowned property = true and a user has typed something in and then presses "Enter". This is not the case if the DropDowned property = false. When that occurs the correct string is returned.

I have even tried having the program select all of the text in the comobox; however, giving a value for the SelectionLength greater than the ComboBox.Text.Length does not appear to work. I have also tried referring to the SelectedValue; however, the SelectedValue is null.

For all intensive purposes the application is convinced that there is a null string in the combobox.

How can I retrieve the actual string?


In case this helps I have code for the following events: Click, DataSourceChanged, DropDown, DropDownClosed, Enter, KeyDown, Leave, and Validated.


This might be a bug: Wrong SelectedItem in DropDownClosed event handler of ComboBox when pressing Tab to leave an opened dropdown

I know it isn't identical to your situation. Check the workaround tab to see if the code posted there helps you out. It's probably just a matter of using the correct events.

My experiences with event orders and selected properties of some Windows Forms controls have been less than favorable.


I was able to create a successful workaround to this apparent bug. Below is my workaround; hopefully, this code will help others. Note: You may need to add other event handlers to fine tune all of your ComoBoxes' user interactions, but this will work for the problem I described in my question.

To use this code you will need a ComboBox on your form called cmbxTest. You will also need to add the appropriate event handlers. Assuming your form name is frmMain as used below, in the fmrMain.Designer.cs file, add this code (note you will want other items too, but these are the new items that will needed to be added to the ComboBox, cmbxTest, that should already be on your test form, frmMain):

this.cmbxTest.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Append;
this.cmbxTest.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
this.cmbxTest.DropDownClosed += new System.EventHandler(this.cmbxTest_DropDownClosed);
this.cmbxTest.KeyUp += new System.Windows.Forms.KeyEventHandler(this.ComboBoxKeyUp);
this.cmbxTest.Text = "Test";  // Used in the below example - The default displayed text

In the class file for the form (frmMain.cs in this example), make it look something like the following:

public partial class frmMain : Form
{
    // Intial Declerations and initializations
    Boolean bReady = false;       // Secondary trigger for DataGridView selection
    string clrTest = "Test";      // Default display text - Clear filter text; Used to ignore the setting if this text is visible
    string currentText;           // Comboboxes' currently displayed text

    // Form execution
    public frmMain()
    {
        InitializeComponent();
    }

    // Some code...

    //
    // ComboBoxes on KeyPress event
    //      - Used as a workaround for MS ComboBoxes not updating their text correctly
    //      - Shared across all ComboBoxes (as applied by the individual controls' event handlers)
    //
    private void ComboBoxKeyUp(object sender, KeyEventArgs e)
    {
        ComboBox cmb = (ComboBox)sender;
        currentText = cmb.Text;
    }

    // Any trigger you want that requires the ComboBoxes text
    private void cmbxTest_DropDownClosed(object sender, EventArgs e)
    {
        if (!cmbxTest.Text.Equals(clrTest))
        {
            cmbxTest.Text = currentText;
        }
        // Do any other code that requires the cmbxTest.Text
        Console.WriteLine(cmbxTest.Text);
    }
}
链接地址: http://www.djcxy.com/p/60902.html

上一篇: 仅从组合框中选择列表项

下一篇: ComboBox.Text =空字符串,而不是实际显示的字符串