C# 文本框为空时如何输入默认值
我有一个C# 文本框为空时如何输入默认值,c#,winforms,methods,textbox,operand,C#,Winforms,Methods,Textbox,Operand,我有一个方法,它对文本框中的值进行求和,我想改进它,如果这些文本框中的任何一个为空,我想在其中插入“0”,但我不知道该在哪里以及具体放什么才能让它像我想要的那样工作。这件事我想了很久了,有人能给我提点建议吗 void vypocti_naklady() { double a, b,c,d,e,f,g,h; if ( !double.TryParse(p_ub_s.Text, out a) || !double
方法
,它对文本框
中的值进行求和,我想改进它,如果这些文本框
中的任何一个为空
,我想在其中插入“0”
,但我不知道该在哪里以及具体放什么才能让它像我想要的那样工作。这件事我想了很久了,有人能给我提点建议吗
void vypocti_naklady()
{
double a, b,c,d,e,f,g,h;
if (
!double.TryParse(p_ub_s.Text, out a) ||
!double.TryParse(p_poj_s.Text, out b) ||
!double.TryParse(p_jin_s.Text, out c) ||
!double.TryParse(p_dop_s.Text, out d) ||
!double.TryParse(p_prov_s.Text, out e) ||
!double.TryParse(p_pruv_s.Text, out f) ||
!double.TryParse(p_rez_s.Text, out g) ||
!double.TryParse(p_ost_s.Text, out h)
)
{
naklady.Text = "0";
return;
}
naklady.Text = (a+b+c+d+e+f+g+h).ToString();
}
感谢大家的帮助和时间。private double GetValue(字符串输入)
private double GetValue(string input)
{
double val;
if(!double.TryParse(input,out val))
{
return val;
}
return 0;
}
var sum = this.Controls.OfType<TextBox>().Sum(t => GetValue(t.Text));
{
双val;
如果(!double.TryParse(输入,输出值))
{
返回val;
}
返回0;
}
var sum=this.Controls.OfType().sum(t=>GetValue(t.Text));
试试上面的方法。只需在文本框的父对象上运行OfType(父对象可以是表单本身)
这会将任何无效输入计算为0,请尝试以下操作:
// On the textboxes you want to monitor, attach to the "LostFocus" event.
textBox.LostFocus += textBox_LostFocus;
这将监视文本框何时失去焦点(已从中单击)。如果有,则运行以下代码:
static void textBox_LostFocus(object sender, EventArgs e) {
TextBox theTextBoxThatLostFocus = (TextBox)sender;
// If the textbox is empty, zeroize it.
if (String.IsNullOrEmpty(theTextBoxThatLostFocus.Text)) {
theTextBoxThatLostFocus.Text = "0";
}
}
如果您观看
TextBox.LostFocus
事件。然后,当用户离开该框单击时,它将运行textBox\u LostFocus
。如果TextBox
为空,则我们将该值替换为零。您可以创建一个TextBox验证事件(因为如果为空,则只需插入0而不保留焦点),并将所有其他文本框订阅到该TextBox验证事件
例如:您有5个文本框订阅(通过单击例如textbox1 properties window | events并双击validated),对于其他文本框,将其已验证的事件订阅到该文本框,然后在其中放置以下内容:
private void textBox1_Validated(object sender, EventArgs e)
{
if (((TextBox)sender).Text == "")
{
((TextBox)sender).Text = "0";
}
}
另一种方法是不直接使用
TextBox
文本并对其进行解析,而是将其数据绑定到属性并使用它们。绑定
本身将进行解析和验证,使变量始终保持干净,随时可用
public partial class Form1 : Form
{
// Declare a couple of properties for receiving the numbers
public double ub_s { get; set; }
public double poj_s { get; set; } // I'll cut all other fields for simplicity
public Form1()
{
InitializeComponent();
// Bind each TextBox with its backing variable
this.p_ub_s.DataBindings.Add("Text", this, "ub_s");
this.p_poj_s.DataBindings.Add("Text", this, "poj_s");
}
// Here comes your code, with a little modification
private void vypocti_naklady()
{
if (this.ub_s == 0 || this.poj_s == 0 /*.......*/)
{
naklady.Text = "0";
return;
}
naklady.Text = (this.ub_s + this.poj_s).ToString();
}
}
您只需处理属性,这些属性已经安全地键入为
double
,而不必考虑格式化和解析。您可以通过将所有数据移动到ViewModel
类并将逻辑放在那里来改进这一点。理想情况下,您也可以通过数据绑定将相同的想法应用到输出文本框
,但要实现这一点,您必须实现INotifyPropertyChanged
,以便绑定知道何时更新UI。@sircodesalot-WinForms,谢谢您的时间。