conker87 conker87 - 1 month ago 15
C# Question

Set focus back on a ComboBox if the value is incorrect

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?

Answer

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()