Question

public int dialog()
{
    Form prompt = new Form(); // creates form

    //dimensions
    prompt.Width = 300;
    prompt.Height = 125;

    prompt.Text = "Adding Rows"; // title

    Label amountLabel = new Label() { Left = 75, Top = 0, Text = "Enter a number" }; // label for prompt
    amountLabel.Font = new Font("Microsoft Sans Serif", 9.75F);
    TextBox value = new TextBox() { Left = 50, Top = 25, Width = prompt.Width / 2 }; // text box for prompt
    Button confirmation = new Button() { Text = "Ok", Left = prompt.Width / 2 - 50, Width = 50, Top = 50 }; // ok button
    confirmation.Click += (sender, e) => { prompt.Close(); }; // if clicked it will close

    prompt.AcceptButton = confirmation; // enter

    // adding the controls
    prompt.Controls.Add(confirmation);
    prompt.Controls.Add(amountLabel);
    prompt.Controls.Add(value);
    prompt.ShowDialog();

    int num;
    Int32.TryParse(value.Text, out num);
    return num;
}

This is what my prompt looks like when it's called

Prompt

I just clicked a button to call that method. Now as you notice, the text box is not selected. How do I make it so that if this method is called, it will make the text box selected by default without having to click it or tab to it?

(I know this is minor but every detail would look nicer)

Was it helpful?

Solution

The order used to tab between controls is determined by the property TabIndex. This property is determined automatically by the order in which you add the controls (If you don't change it manually) The control with TabIndex = 0 will be focused at the opening of the form (Of course if the control could be focused)

Try with

prompt.Controls.Add(value);
prompt.Controls.Add(confirmation);
prompt.Controls.Add(amountLabel);
prompt.ShowDialog();

OTHER TIPS

You mean Focused ? Like this:

textBox1.Focus();

Write this code after your show dialog,It should work.

prompt.ShowDialog();
prompt.Controls.OfType<TextBox>().First().Focus();

Or if it doesn't work try to set ActiveControl property before opening your prompt:

promt.ActiveControl = value;
prompt.ShowDialog();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top