1. "Do not confuse warm with soft"
The first and main error is that you are trying to cram all the program logic into event handlers. You do not need to do this, because if you need to slightly change the logic, you will have to go into the code of visual components, etc. etc. with all the headaches it causes.
Event handler code should be as short and simple as possible. There are usually quite a lot of events and handlers and it is easy to get confused in them. Especially if pieces of code are simply copied from the handler to the handler.
2. We separate model and representation
In the simplest case, it is enough to create a separate class or set of classes for storing and processing data. Let's call this class conditionally MyModel . In this class, define the fields for storing data and the method for loading them, for example
public void LoadData() in which you make all the necessary actions to get data. You also define properties in this class for controlled access to data and transfer them to visual components for display and, possibly, modification.
3. How does it look and how to use it?
Determine the model
public class MyModel { public int MyData1 { get; private set; }//свойство только для чтения public string MyData2 { get; set; }//свойство для чтения и записи ... //остальные нужные свойства ... public void LoadData() { MyData1 = 100500;//замените на вашу логику получения данных MyData2 = "I'm cool string"; } ... //остальная логика работы с данными модели }
now in shape
public class MainForm : Form { private MyModel model;//форма должна знать что у нее есть модель, //поэтому размещаем ссылку на нашу модель private void MainForm_Load(object sender, EventArgs e) { //Инициализируем модель и загружаем данные model = new MyModel(); model.LoadData(); //Настраиваем таймер timer_update.Interval = IntervalUpdate; timer_update.Tick += new EventHandler(TickHandler); timer_update.Enabled = true; } private void TickHandler(object sender, EventArgs e) { model.LoadData(); } //далее все остальное что там нужно }
Already noticed the difference? Even if you need to change the logic of data loading, you will do it in one single place and not suffer from copy-paste errors. If you need to change the visual components - this, again, will not affect the model.
The example is greatly simplified, and far from ideal, although it is quite suitable for an application with one main form. Read more in the literature on design patterns (disign patterns), for example, here to start. As applied to WinForms, MVP (Model-View-Presenter) or MVPVM is the closest, but the latter is more complex and there is not always a real need, but I recommend to get acquainted with all the patterns and anti-patterns in order to have a basic idea of how, when and why they are applied, even if you don’t figure it out right away - it’s not scary, understanding will come with time and experience, well, or ask another question here =)