There are 3 related tables in the database. I want to make a class in which there will be variables with the name of all columns from 3 tables, and methods that would make selections and write data to these variables. And on the form, this data was displayed on the components. Conversely, when writing, the data from the form would be transferred to variables of this class and recorded in the database. I do this so that in the class all sorts of checks for null are carried out, for compliance, in some data the value is increased by 1 (this is for the Index in the ComboBox), etc. It seems like I did everything:

public class PreBlock { public int BlockNumber; public string BlockIndex; public int BlockMass; public int Category; public string CritOtkl; public string OtklSKP; //Аппарат востановления public int VostProcNumber; public int nCondensat; public int nVostRetorta; public int nVostCover; public int nChvost; public int nSlivPipe; // ... и еще много других переменных из таблиц //метод для выборки по заданому блоку public void Prepare(int block) { //здесь обычная выборка и запись во все вышеперечисленные переменные } public void saveBlock { //здесь наоборот запись в таблицы по данным из переменных } } //класс формы public partial class Blocks : Form { PreBlock bl; //объект класса int block; //номер блока для выборки Prepare public Blocks() { //создаю объект класса и запрос bl = new PreBlock(); bl.Prepare(block); //далее уже присваиваю значение компонентам из класса BlockMass.Value = bl.BlockMass; Category.Value = bl.Category; //далее по аналогии присваиваю } //перед сохранением присваиваю значение компонентов переменным из класса PreBlock public void SyncBlock() { bl.BlockMass = BlockMass.Value; bl.Category = Category.Value; //далее по аналогии присваиваю //и вот тут возникает ошибка: //"Ссылка на объект не указывает на экземпляр объекта." } 
  • Yes, I was sealed to be Blocks (). And I call the SyncBlock () method on the "Save" button - zerpico
  • How it was not created if Blocks () is called when creating a class object, everything is fine, everything is causing a problem then in the SyncBlock () method - zerpico
  • You are not confused by what you call the public methods, then with a large, then with a small letter? Not to mention the public fields, the change of which can break the internal state. - nitrocaster
  • @Pandacun are you sure that a class that simulates three tables at the same time is a good idea? If so, are you sure that your database is properly designed? And generally, maybe it makes sense to use ORM? - DreamChild
  • block is just an int variable, and in Preblock (block) it is just the value for the key field in the sample that links all 3 tables: SELECT * FROM BlockTg WHERE BlockNumber = block Just a mixed query from 3 tables. 2 of which are essentially just lists for the ComboBox on the form. Yes, and that with which letter it starts to work does not affect (I understand the rules of good form and all that, but I understand everything, especially since I comment on each method). I do not know anything about ORM. I just have an error when calling SyncBlock () - zerpico

2 answers 2

So, first a few words about the code. To make it clear what was going on, here it is .

Dear @Pandacun , please do not be offended, what I say below may seem unpleasant to you. So, your code is disgusting. In it, you violate all the principles of programming / design that can be violated.

First, you lump the view, model, and controller together. (Be sure to read about MVC ). Secondly, you have in one class both event handling, and setting the UI states, and working with the database (already with three tables) and the devil knows what (the “Divine Object” antipattern), thirdly you “suppress” the exception in the designer and you hammer the designer himself with tons of some strange actions. Fourth, you completely forget about encapsulation , making the class fields public. Fifth, you have unreasonably exaggerated methods of your classes. Sixth, terrible identifiers - all of these dataReader1 and nVostStove2 with a mix of Microsoft- and Java-style naming (a trifle on the one hand, and on the other hand, it tells about your lack of organization)

As for ORM, this is a very useful and convenient technology that allows you to get rid of a number of problems, including yours.

And specifically by your mistake. Apparently, when you refer to BlockText, it does not exist. This is probably due to the fact that you, in an event handler belonging to one form, are trying to access the BlockText element lying on the other. I do not see any other intelligible reasons for this, and judging this by the kilometer-wide code wrapper without referring to your UI is quite problematic.

Anyway, @Pandakun , all of the above is not said to tell the world how stupid you are as a programmer, but to point out possible ways to improve your code, so don’t take it as something personal. Probably, you are not a very experienced developer, so what I am telling you about may seem to you as insignificant nonsense, but believe me, it really makes sense.

  • Yes, no BlockText then I have the same form. But the problem was solved in a different way. The form constructor creates an instance of the class, makes a request, fills the form components with data. Using the save button, I create an instance of the class (because the first one disappeared when the method was completed), I filled the class variables with data, and saved it to the database (the method is in the Preblock class). Well, yes, the code is terrible, generally alter someone else doubly terrible. But yes you are right, I still know little, I generally programmed in Delphi before. And about the name of the variables, well, I did not come up with such names - goo.gl/uk5cpt . And I would like to learn of course. - zerpico
  • I read about MVC, to be honest, I didn’t understand much, and I didn’t find the same simple example. But I understood business logic model better, of course, I understand that I don’t have it. But I just read about it for now. - zerpico
  • such things are best given in combination of theory and practice - DreamChild
  • About MVC, everything is so beautifully painted, it became scary. But I doubt that in the real case it will take root, especially in the factory where I work. For example, the base on which I am working now BEFORE ME looked like this - goo.gl/8qYfrq And after that I redid the base - goo.gl/J8yHCM . In some fields, the numbers were separated by spaces (this is how the lists were organized). Table Block is generally a quiet horror - 121 columns. So now there is even less structure. But of course it's far from ideal, but this client has to be cut correctly, but I don’t know yet. - zerpico

I think you need to look in the direction of ORM.
Your implementation mixes the logic of the code, is suboptimal and surely there are a lot of bugs and jambs in it.
ORM will relieve you of the majority of similar trifles (in the presence of direct hands, of course).
For example, Entity Framework , NHibernate .

  • Why make a fuss, there is not all that difficult. Just a mixed query from 3 tables. 2 of which are in fact just lists for ComboBox on the form, so I don’t think it makes sense to build it, especially since I don’t know anything about it yet - zerpico
  • 2
    The fact is that your code is only suitable inside the university, and even good teachers will reject it. At work for such a head will not stroke. Therefore, it is worth learning right things right away, as one of a great many - ORM. - mrakolice
  • one
    @Pandacun: Everything is already difficult here. When you pack all the complexity into one unfortunate class, you (and no one else) cannot fit all the internal conditions in the head, all the rules, what is initialized for what and at what point what can be expected. If it were simple, you would not ask a question here. Rewrite code on MVC, break into levels, and then it will be easy. In the meantime, unnecessarily difficult. And yes, do not regret classes. Bytes have recently fallen in price, do not press. - VladD
  • one
    @VladD funny situation - the illusory simplicity of the code, which is difficult to perceive due to unsuccessful design. As a result, from a certain moment only the author can understand him - DreamChild
  • one
    @DreamChild: Yeah, that’s it. For some reason, many people think that throwing everything together is easier. It's easier to write - yes, it's easier to understand and work with the code - not at all. - VladD