C# Windows Form - How to Reuse an Object from a Different Button Click Event

825 views Asked by At

I am building a Windows Form where I am connecting to HP Quality Center OTA. I am able to login to the system but after logging out when I click to the Login button the previous instance of the object doesn't get reinitialized. Is there a way to reuse the same object or is there a different approach I should be taking? Here is the code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TDAPIOLELib;

namespace TestLab
{


public partial class Form1 : Form
{

    static TDConnection tdc = new TDConnection();
    static String qcUrl = "https://serveraddress/qcbin";
    static string uid;
    public Form1()
    {
        InitializeComponent();
    }

    private void login_button1_Click(object sender, EventArgs e)
    {
        uid = Microsoft.VisualBasic.Interaction.InputBox("Enter your User ID", "User ID", " ", 0, 0);
        string pwd1 = Microsoft.VisualBasic.Interaction.InputBox("Enter your password", "Password", " ", 0, 0);

   //     TDConnection tdc = new TDConnection();
        tdc.InitConnectionEx(qcUrl);
        tdc.Login(uid, pwd1);

        label1.Text = " ";
        label1.Text = uid + " logged into HPQC.";

    }

    private void label1_Click(object sender, EventArgs e)
    {

    }

    private void logout_button1_Click(object sender, EventArgs e)
    {
        tdc.Logout();
        tdc.Disconnect();
        tdc = null;
        label1.Text = " ";
        label1.Text = uid + " logged out of HPQC.";
    }
}

}

1

There are 1 answers

5
Steve On BEST ANSWER

In the Logout code you set the global variable tdc to null. Of course this means that you need to reinitialize it with a call to new TDConnection

You seems to have two options.

  1. Remove the line that sets the tdc variable to null in the logout code. Leave everything else unchanged
  2. Do not initialize the variable tdc at the global level but just everytime you enter the login code and leave the line that sets the variable tdc to null in the logout code.

Consider also that these kind of objects usually implements the IDisposable interface. If it is the same with your TDConnection class then it is probably better to call the Dispose method in the logout code