Object reference not set to an instance of an object error when perform auto click method

StackOverflow https://stackoverflow.com/questions/23194481

  •  06-07-2023
  •  | 
  •  

سؤال

I have a code and perform auto click method something like this:

public partial class cron_printer : Form
{
    public cron_printer()
    {
        InitializeComponent();
        cmdCommand_Click(null, null);
        dbConnect = new DBConnect();

    }
    private void cmdCommand_Click(object sender, EventArgs e)
    {
        List<string>[] list;
        //get list from database
        list = dbConnect.Connect(); //ERROR:Object reference not set to an instance of an object.
        for (int i = 0; i < list[0].Count; i++)
        {
            string ipAdd = list[0][i]; 
            CmdConnect(ipAdd, txtPort.Text); //call function connect
        }
    }
}

If I create a button named cmdCommand and perform normal click, the code work fine. But when I perform auto click method by adding this line:

cmdCommand_Click(null, null);

then I get the error as commented in the code. Any idea?please advise.

هل كانت مفيدة؟

المحلول

When cmdCommand_Click(null, null); Excuted, dbConnect is still NULL. please try this:

public cron_printer()
{
    InitializeComponent();        
    dbConnect = new DBConnect();
    cmdCommand_Click(null, null);
}

نصائح أخرى

you are calling the cmdCommand_Click event before initialising the object dbConnect.

You should first initialise the object dbConnect first and then call/invoke the cmdCommand_Click event

Replace This:

cmdCommand_Click(null, null);
dbConnect = new DBConnect();

With This:

dbConnect = new DBConnect();
cmdCommand_Click(null, null);

Add the DbConnect() istantiate line in the event:

private void cmdCommand_Click(object sender, EventArgs e)
{
    dbConnect = new DBConnect();
    List<string>[] list;
    //get list from database
    list = dbConnect.Connect(); //ERROR:Object reference not set to an instance of an object.
    for (int i = 0; i < list[0].Count; i++)
    {
        string ipAdd = list[0][i]; 
        CmdConnect(ipAdd, txtPort.Text); //call function connect
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top