Lambros Hitiris Lambros Hitiris - 7 days ago 6
C# Question

C# - Change label text from another class

I am a total noob on C# and I'm stuck on changing the status label text from an other class.

When this class connects to db I want to change the label text to "Connected":

public class DBConnect
{
public void Connect()
{
MySqlConnection conn;
string myConnectionString;

myConnectionString = "server = 127.0.0.1; uid=cardb;" +
"pwd=cardb; database=test;";

try
{
Form form = new Form();
conn = new MySqlConnection();
conn.ConnectionString = myConnectionString;
conn.Open();
form.setStatus();
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}
}
}


This is the method setStatus I created in Form class:

public partial class Form : System.Windows.Forms.Form
{
public Form()
{
InitializeComponent();
}

public void setStatus()
{
StatusTextLabel.Text = "Connected";
}


The label text doesnt change though.. :/

Answer

I see no code to create a DBConnect object, or to call its Connect() method, and no code that makes the Form object visible, e.g. form.Show().

Other than that you probably should not create the Form from the Connect method; instead call Connect() from the Form, e.g. in Form_Load(), let it return a status, or better: the conn object (which you are now throwing away after connection), and make Form_Load set the Label.Text based on that.

Example code:

private void Form1_Load(object sender, EventArgs e)
{
    var conn = new DBConnect().Connect();
    if (conn != null && conn.State == ConnectionState.Open)
    {
        StatusTextLabel.Text = "Connected";
    }
}

public class DBConnect
{
    public SqlConnection Connect()
    {
        SqlConnection conn = ...
        // ...
        return conn;
    }
}
Comments