从对话框窗口获取值

时间:2013-10-30 19:48:52

标签: c# .net winforms visual-studio-2012

我无法获取弹出对话框的文本框的值。我遵循了其他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保持为null。难道我做错了什么?谢谢!

2 个答案:

答案 0 :(得分:5)

对于初学者,名为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'");
        }
    }
}

答案 1 :(得分: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事件中执行这些行,如果您没有按钮让他们单击以“提交”其值。

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

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