I am new to C# and I want to apply low coupling to my project. I have two classes wherein one is a form and the other is a regular class. I can easily use instances in both forms(my other form) but can't seem to work if I connect a form and the regular class as I've stated. It shows (Object reference not set to an instance of an object). How can I fix this?
My significant codes in the form:
namespace MMCM_Library
{
public partial class MMCMLibrary_home : Form
{
public static MMCMLibrary_home instance;
//DCR1 Labels
public Label lbl1_1, lbl1_2, lbl1_3, lbl1_4;
//DCR1 Labels
public Label lbl2_1, lbl2_2, lbl2_3, lbl2_4;
//DCR1 Labels
public Label lbl3_1, lbl3_2, lbl3_3, lbl3_4;
//DCR1 Labels
public Label lbl4_1, lbl4_2, lbl4_3, lbl4_4;
ReadandWrite read = new ReadandWrite();
TimeFrame_Colors TimeFrame = new TimeFrame_Colors();
public MMCMLibrary_home()
{
InitializeComponent();
instance = this;
TimeFrame.Colors();
//DCR1
lbl1_1 = lblDCR1_9;
lbl1_2 = lblDCR1_11;
lbl1_3 = lblDCR1_1;
lbl1_4 = lblDCR1_3;
//DCR2
lbl2_1 = lblDCR2_9;
lbl2_2 = lblDCR2_11;
lbl2_3 = lblDCR2_1;
lbl2_4 = lblDCR2_3;
//DCR3
lbl3_1 = lblDCR3_9;
lbl3_2 = lblDCR3_11;
lbl3_3 = lblDCR3_1;
lbl3_4 = lblDCR3_3;
//DCR4
lbl4_1 = lblDCR4_9;
lbl4_2 = lblDCR4_11;
lbl4_3 = lblDCR4_1;
lbl4_4 = lblDCR4_3;
}
My class:
I used trial and error
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MMCM_Library
{
internal class TimeFrame_Colors : Form
{
ReadandWrite read = new ReadandWrite();
public static TimeFrame_Colors instance;
public void Colors()
{
instance = this;
//COLOR OF DCR1_9
if (read.readExcel(1, 1) == "0")
{
MMCMLibrary_home.instance.lbl1_1.BackColor = System.Drawing.Color.Red;
}
else if (read.readExcel(2, 2) == "1")
{
MMCMLibrary_home.instance.lbl1_1.BackColor = System.Drawing.Color.Red;
}
CodePudding user response:
public MMCMLibrary_home()
{
InitializeComponent();
instance = this;
//Because lbl1_1 is null value
//You need to call TimeFrame.Color() after asign lbl1_1~lbl4_4
//TimeFrame.Colors();
//DCR1
lbl1_1 = lblDCR1_9;
lbl1_2 = lblDCR1_11;
lbl1_3 = lblDCR1_1;
lbl1_4 = lblDCR1_3;
//DCR2
lbl2_1 = lblDCR2_9;
lbl2_2 = lblDCR2_11;
lbl2_3 = lblDCR2_1;
lbl2_4 = lblDCR2_3;
//DCR3
lbl3_1 = lblDCR3_9;
lbl3_2 = lblDCR3_11;
lbl3_3 = lblDCR3_1;
lbl3_4 = lblDCR3_3;
//DCR4
lbl4_1 = lblDCR4_9;
lbl4_2 = lblDCR4_11;
lbl4_3 = lblDCR4_1;
lbl4_4 = lblDCR4_3;
TimeFrame.Colors();
}
CodePudding user response:
You are calling lbl1_1.BackColor
before assigning a value to lbl1_1
.. Move TimeFrame.Colors();
call to the end of the constructor.