从对话框窗口中获取值

本文关键字:获取 窗口 对话框 | 更新日期: 2023-09-27 18:37:28

我在获取弹出对话框的文本框的值时遇到问题。我遵循了其他 StackOverflow 问题的建议,这些问题说要在程序中创建一个公共变量.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保持无效。我做错了什么吗?谢谢!

从对话框窗口中获取值

对于初学者来说,名为Cash的表单应该使用面向对象设计。 它应该有一个名为 CashEntered 的公共属性或类似类型 decimal 而不是字符串的属性。 您可以像这样调用表单:

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
    }
}

使用静态变量来保存临时对话框的结果是一种不好的做法。 下面是对话框的更好实现:

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'");
        }
    }
}

在要获取其值的主窗体上,您将拥有这样的代码;

        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事件中执行这些行。

编辑 您可能希望在 btnClose 事件内的文本框中添加某种验证,例如:

 decimal myDecimal;
 if (decimal.TryParse(textBox1.Text, out myDecimal))
 {
      this.DialogResult = DialogResult.OK;
      this.Close();
 }
 else
 {
     MessageBox.Show("Invalid entry", "Error");
     textBox1.SelectAll();
 }