Hello! Please help me with the class declaration. There are two forms. On Form1 are comboBox1 , textBox1 . In Program.cs I declare a class:

 namespace Test { static class Program { static void Main() { Application.Run(new Form1()); } } public class Data { public string subject; public string variant; public string Subject(Form1 Form1) { subject = Form1.comboBox1.SelectedItem.ToString(); return subject; } public string Variant(Form1 Form1) { variant = Form1.textBox1.Text; return variant; } } } 

Next, in Form2 I try to access the fields of the Data.subject and Data.variant , but for some reason they are null .

 namespace Test { public partial class Form2 : Form { // Внешние переменные: System.IO.StreamReader Reader; Data Data = new Data(); public Form2() { InitializeComponent(); var Charset = System.Text.Encoding.GetEncoding(1251); // Должен открыться файл, но не открывается из-за пустых значений Reader = new System.IO.StreamReader (@"\Вопросы\" + Data.subject + @"\Вариант " + Data.variant + ".txt", Charset); } } } 

Tell me, please, what am I doing wrong?

  • four
    And you have not tried to start some book on C # to read? - Donil
  • @Cirran, please use Cyrillic. - smackmychi
  • You violated all the thoughts and unbelievable principles of the PLO, as you do, you can not do! Interface and logic in the same class is not allowed. Classes need to be created in separate files, and as parameters not to take controls, but the values ​​that these controls contain. - beliy26rus September

1 answer 1

Without field initialization, they will be null. Try to make a private field of type Form1 and a Data constructor (Form1 form) of something like:

  private Form1 _form; public Data (Form1 form) { _form=form; } 

Well, in Subject and Variant use the internal variable _form.

Use not Data.subject, but Data.Subject, and not Data.variant, but Data.Variant.

Something like that, if fast ....