【问题标题】:Comparing textBox1.Text and textBox2.Text比较 textBox1.Text 和 textBox2.Text
【发布时间】:2014-10-07 15:53:57
【问题描述】:

所以我有这个代码

public partial class Form1 : Form
{
    public string str;
    public string str2;
    public Form1()
    {

        InitializeComponent();
        str = textBox1.Text;
        str2 = textBox2.Text;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (String.IsNullOrEmpty(textBox1.Text))
        {
            MessageBox.Show("Enter Material Name Please.");     
        }

        if (str == str2)
        {
            MessageBox.Show("Materials are equal.");
        }

        else if (str != str2)
        {
            MessageBox.Show("Materials don't match.");
        }
    }
}

我想你会猜到我想在这里做什么..你能告诉它有什么问题吗?我是几天前开始的,所以请原谅我缺乏知识。

【问题讨论】:

  • 你想和两个textbox比较什么?
  • 您只需要在问题中包含代码的相关部分,空方法不会成为问题的原因。

标签: c#


【解决方案1】:

您只在构造函数中初始化这些字符串一次,而不是在点击事件处理程序中。您还可以使用属性将控件与字符串进行映射,从而使代码更具可读性和健壮性:

// use meaningful control/variable names
string Material1 
{
    get { return textBox1.Text; }
    set { textBox1.Text = value; }
}

string Material2
{
    get { return textBox2.Text; }
    set { textBox2.Text = value; }
}

private void button1_Click(object sender, EventArgs e)
{ 
    if (String.IsNullOrWhiteSpace(Material1)) // handles also multiple spaces
    {
        MessageBox.Show("Enter Material Name Please.");  
        // return; <-- perhaps?   
    }

    if (Material1 == Material2)
    {
        MessageBox.Show("Materials are equal.");
    }
    else
    {
        MessageBox.Show("Materials don't match.");
    }
}

【讨论】:

  • 可能是操作人员了解引用和值的好时机,当然,另一种选择是操作人员在我编辑的空 text_changed 事件中更新 strstr2
  • 这不是必需的,但是在空检查测试中的消息框之后的返回语句可能是一个改进。假设如果 material1 为空,OP 不想测试相等性。
  • @failedprogramming:我确信这可以在很多方面得到改进,但在这里继续下去并不是一个错误。我还想专注于本质(我已经使用属性将字符串与控件映射)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-25
  • 1970-01-01
  • 2011-08-05
  • 2019-11-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多