Comparing textBox1.Text and textBox2.Text

本文关键字:Text textBox2 and Comparing textBox1 | 更新日期: 2023-09-27 18:25:55

所以我有这个代码

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

我想你会猜到我在这里想做什么。。你能说出它出了什么毛病吗?我是几天前开始的,所以请原谅我缺乏知识。

Comparing textBox1.Text and textBox2.Text

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

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