简体   繁体   中英

How to pass a string variable data from Form2 to Form1?

It's a program that reads student data from a text file and displys it in a listbox(Form1). From there on you can add a new student to the textfile by clicking on "Add" button that shows another form(Form2) and you input the new student data into the appropriate text boxes. Afterwards you can press "Add" button(Form2), but the Add Student(Form2) window comes up again with all the inputted data gone, and if I place the new student info into the text boxes again and click "Add", the program jumps back to the Form1 and a message box suppose to say what was added to the textfile, but nothing was added except for empty listbox items.

Normally Form1 instantiates Form2 and shows it. You could add a public property getter on Form2 which will contain the necessary information and Form1 could fetch it from the instance of Form2 when needed.

I think you have the assignments backwards; you're setting the textbox values to elements of the string array, which are all null because they were never set. Try that first.

Another thing you could do is place the instance of the data array on Form1, and pass it by reference to Form2's constructor. That way, Form2's job is simply to collect data, and doesn't really have to know implementation details about Form1; all it needs is an array of strings (or preferably a class with named properties) in which to store its data. Form1 can then examine the DialogResult of Form2, and if it's "OK" then Form1 knows that there's data in the array it passed to Form2, and it can handle manipulation of its own ListView and writing to the file.

在第二个窗体上创建属性,然后在第一个窗体上检查属性以获取值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM