2017-06-21 50 views
0

以下问题 我有一个WinForm应用程序,我将通过用户输入设置变量,这里只有字符串,十进制或int。这通过在文本框中输入值或通过按钮(增加和减少)在文本框中设置值来实现。还有两个复选框对(2x是/否)。复选框也保存我需要的值中的字符串。C#验证,如果所有变量已经填写之前退出表格

将值输入到文本框中或设置为正确的数字后,用户按下保存按钮(每个值一个按钮,共6个保存按钮)。保存按钮始终确保输入正确的值之前保存

在关闭表单之前,我想检查是否所有需要的值都已填充,如果没有,请告诉用户:嘿,您忘记了某些值。我怎么能做到这一点?在我的例子中,我想检查Height,Unit和No_of _measure是否填充了一个值。我可以将它全部变成一个大的“if”,其中包含逻辑“或”(总共约14个值),但是我没有得到缺少的具体值,如果没有填充(告诉用户)

例如:

public decimal Height { get; private set; } 
    public int No_of_measure { get; private set; } 
    public string Unit { get; private set; } 

    private void button3_Click(object sender, EventArgs e) //Save the rough heigth 
    {              
     if (textBox2.Text == "") 
     { MessageBox.Show("No value detected in [Current Height] Window. Please Click Start first!"); } 
     else 
     { 
      Height = Convert.ToDecimal(textBox2.Text); 
     } 
    } 

    private void button5_Click(object sender, EventArgs e) //save no. of measurements 
    { 
     if (textBox5.Text == "") 
     { MessageBox.Show("Please enter a value"); } 
     else 
     { No_of_measure = Convert.ToInt32(textBox5.Text); } 
    } 

    private void checkBox3_CheckedChanged(object sender, EventArgs e) //save Unit mm 
    { 
     if (checkBox3.Checked == true) 
     { 
      checkBox4.Checked = false; 
      Unit = "mm"; 
     } 
     label22.Text = "mm"; 
     label23.Text = "mm"; 
+1

这是一个Windows窗体应用程序,Web应用程序? – mjw

+0

它是一个WinForm应用程序。我会把它写入说明 – Chris

+0

可以请你发布条件你已经尝试过 –

回答

0

至于如何在多个属性检查空,粗略的方式将您的值存储在一个字典,你可以按照以下运行LINQ查询。这将要求您对表单进行重大更改。

// properties dictionary populate with your values 
    Dictionary<string,string> _propertiesDictionary = new Dictionary<string, string>(); 

    private bool PropertyChecks() 
    { 
     return _propertiesDictionary.Any(x => x.Value == null); 
    } 

您可以创建一个form_closing事件的方法,把你需要这个,例如内部的任何逻辑..

private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e) 
    { 
     if (PropertyChecks()) 
     { 
      MessageBox.Show("Some properties are null"); 
      e.Cancel = true; 
     } 
    } 
+0

我想你只是创建了一本字典,并没有添加任何属性。 –

+0

正确,对不起,我很忙..他们会填充这个第一个空值使用正确的密钥作为标识 – uk2k05

+0

,但我不认为这将工作,因为我们需要更新此字典,无论何时我们正在更新属性 –