1

我无法获取弹出对话框的文本框的值。我遵循了其他 StackOverflow 问题的建议,这些问题说要在 program.cs 中创建一个公共变量:

public static string cashTendered { get; set; } 

然后我像这样创建了我的对话框:

Cash cashform = new Cash();
cashform.ShowDialog();

当用户按下对话框上的按钮时,这被称为:

        if (isNumeric(textBox1.Text, System.Globalization.NumberStyles.Float))
        {
            Program.cashTendered = textBox1.Text;
            this.Close();
        }
        else
        {
            MessageBox.Show("Please enter a valid amount of cash tendered. E.g. '5.50'");
        }

然而 Program.cashTendered 保持为空。难道我做错了什么?谢谢!

4

2 回答 2

5

For starters your form called Cash should use an object oriented design. It should have a public property called CashEntered or something similar of type decimal instead of string. You would call the Form like so:

using (var cashDialog = new CashDialog())
{
    // pass a reference to the Form or a control in the Form which "owns" this dialog for proper modal display.
    if (cashDialog.ShowDialog(this) == DialogResult.OK)
    {
        ProcessTender(cashDialog.CashEntered);
    }
    else
    {
        // user cancelled the process, you probably don't need to do anything here
    }
}

Using a static variable to hold the results of a temporary dialog is a bad practice. Here is the better implementation of a dialog:

public class CashDialog : Form
{
    public decimal CashEntered { get; private set; }

    private void ok_btn_Clicked
    {
        decimal value;
        if (Decimal.TryParse(cashEntered_txt.Text, out value))
        {
            // add business logic here if you want to validate that the number is nonzero, positive, rounded to the nearest penny, etc.

            CashEntered = value;
            DialogResult = DialogResult.OK;
        }
        else
        {
            MessageBox.Show("Please enter a valid amount of cash tendered. E.g. '5.50'");
        }
    }
}
于 2013-10-30T19:57:14.740 回答
0

在您想要获取值的主要表单上,您将拥有类似这样的代码;

        var cashTendered;
        using (var frm = new Cash())
        {
            if (frm.ShowDialog() == DialogResult.OK)
                cashTendered = frm.GetText()
        }

然后在你的对话框表单上,你会有这样的东西:

        public string GetText()
        {
                return textBox1.Text;
        }

        public void btnClose_Click(object sender, EventArgs e)
        {
                this.DialogResult = DialogResult.OK;
                this.Close();
        }

        public void btnCancel_Click(object sender, EventArgs e)
        {
                this.Close();
        }

或者,您可以在 FormClosing 事件中的 btnClose_Click 事件中执行这些行,而不是如果您没有按钮让它们单击以“提交”它们的值。

Edit You might want to add some sort of validation on your textbox inside the btnClose event, such as:

 decimal myDecimal;
 if (decimal.TryParse(textBox1.Text, out myDecimal))
 {
      this.DialogResult = DialogResult.OK;
      this.Close();
 }
 else
 {
     MessageBox.Show("Invalid entry", "Error");
     textBox1.SelectAll();
 }
于 2013-10-30T19:55:57.793 回答