Domanda

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
    //value.Focus();
    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;

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

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

So this is my prompt and I want to make a button so that it can close. Now I know this has been asked before but that is because they are using a default form.

This is my CancelButton and what it will do.

prompt.CancelButton = this.Close(); // not working

However, I'm not using a different class. I'm using the same class. What would be the 1 call method/property (without visually editing it in the properties section) to close the button if it is closed?

È stato utile?

Soluzione

Here is another way to close your form with pressing escape button for a model form without placing any cancel button:

prompt.KeyPreview = true;
prompt.KeyDown += (sender, e) => 
{ 
    if (e.KeyCode == Keys.Escape) prompt.DialogResult = DialogResult.Cancel; // you can also call prompt.Close() here
};

Altri suggerimenti

If you need to differentiate between closing with cancel and closing with confirm, then your need two separate buttons

Button cancellation = new Button() 
{ Text = "Cancel", Left = prompt.Width / 2 + 10, Width = 50, Top = 50 }; 

prompt.CancelButton = cancellation;
cancellation.DialogResult = DialogResult.Cancel;

also your confirmation button needs the setting for DialogResult property

confirmation.DialogResult = DialogResult.OK;

so you could get the result of the ShowDialog with

if(DialogResult.OK == prompt.ShowDialog())
{
    int num;
    Int32.TryParse(value.Text, out num);
    return num;
}
else
    return 0; // Or whatever to signal failure

By the way, setting the DialogResult property to something different that DialogResult.None will result in the form closing by itself without any need of a click event to close the form.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top