Вопрос

I am trying to set my ComboBoxes so that the user can either choose from the list or set their own value (the combo box is for a custom resolution so there will be default values or they can give their own).

I am trying to make it so that if their value is incorrect (below 0 or not an Int) then it shows a tooltip and prevents it from losing focus. Here is my code:

private void cmbX_Graphics_Width_LostFocus(object sender, EventArgs e)
{
    int i = 0, width = 0;

    TLQAShared._debug("Lost Focus Fired");

    for (i = 0; i < cmbX_Graphics_Width.Items.Count; i++)
    {
            if (cmbX_Graphics_Width.Text.Equals(cmbX_Graphics_Width.Items[i].ToString()))
            {
                Properties.X.Default.Graphics_Width = int.Parse(cmbX_Graphics_Width.Items[i].ToString());
                TLQAShared._debug("FOUND!");

                return;
            }

            TLQAShared._debug("FOR: " + i.ToString() + "/" + (cmbX_Graphics_Width.Items.Count - 1).ToString() + ": " + cmbX_Graphics_Width.SelectedText + ":" + cmbX_Graphics_Width.Items[i].ToString());
    }

    TLQAShared._debug("Not true: '" + cmbX_Graphics_Width.Text + "'");

    if (int.TryParse(cmbX_Graphics_Width.Text.ToString(), out width))
    {
        TLQAShared._debug("TryParse: true");

        Properties.X.Default.Graphics_Width = width;
    }
    else
    {
        tt.SetToolTip(cmbX_Graphics_Width, "You must supply a valid integer");

        this.ActiveControl = cmbX_Graphics_Width;
        TLQAShared._debug("TryParse invalid.");
    }
}

However if the control loses focus, this code gets executed twice, first time it stops at this part:

TLQAShared._debug("Not true: '" + cmbX_Graphics_Width.Text + "'");

Then does it again but executes the entire code, but does not prevent the control from losing focus.

Two questions I have: Firstly: Is this the best practice and if not what should I do? Secondly: If it is best practice, how would I fix it?

Это было полезно?

Решение 2

I don't think this is a good practice. I would do it like this:

  1. Create a function to check if the input is valid (int > 0)
  2. Call this function when the user attempts to enter the input
  3. If the input isn't valid call combobox.focus()

Другие советы

use combobox1.Select(); for focus in combobox.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top