Global variable won't work in searching in one

2019-03-05 16:55发布

问题:

I made a program that gets info in textbox1 and textbox2 after pressing button1. If you type in textbox3 and if what you wrote there is same as textbox1 ,After pressing button2 it puts textbox2's text in the label2.text.

But the problem is that it won't put the textbox2.text into label2.text. Why?

Here's the code:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    ozv[] a = new ozv[5];
    int i = 0;
    private void button1_Click(object sender, EventArgs e)
    {
        a[i] = new ozv();
        a[i].name = textBox1.Text;
        a[i].id = int.Parse(textBox2.Text);
        i++;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        for (int j = 0; j < 5; j++)
        {
            a[j] = new ozv();
            if (a[j].name == textBox3.Text)
            {
                label2.Text = a[j].id.ToString();
            }
        }
    }
}

And here's the class I made:

class ozv { public string name; public int id; }

回答1:

Remove this line:

for (int j = 0; j < 5; j++)
    {
--->    a[j] = new ozv();
        if (a[j].name == textBox3.Text)

You are erasing what you just saved, this is why you are not getting any result.

Also, check that you a[j] instance is defined:

if (a[j] != null) && a[j].name == textBox3.Text)

You can also break; after you find the first matching occurence, to exit the loop earlier.

Note 1: you should try going step-by-step into your code, and looking at the variable states. This would really help you debug stuff like that.

Note 2: you should consider using a List<ozv> so that you can just iterate over it without having to handle nulls.



标签: c# arrays global