gpt4 book ai didi

c# - 从对话框窗口获取值

转载 作者:太空宇宙 更新时间:2023-11-03 20:11:39 25 4
gpt4 key购买 nike

我无法获取弹出对话框的文本框的值。我听从了其他 StackOverflow 问题的建议,即在 program.cs 中创建一个公共(public)变量:

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 类型的公共(public)属性,而不是字符串。您可以这样调用表单:

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

关于c# - 从对话框窗口获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19692514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com