user8427711
user8427711

Reputation:

Objects from another Class In C#

I want to 2 Classes (1 Form class) in form class, I call Another Class void. It works And I want do thigs with labels and textboxes (in second class script) I saw this How to change a label from another class? c# windows forms visual studio and my code :

`private new void Enter(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == Convert.ToChar(Keys.Enter))
            {
                Commands.OnCommand();`

other class :

public static void OnCommand()
    {
        Form1 frm = new Form1();
        if (frm.code.Text.Contains("end") && frm.code.TextLength == 4)
        {
            if (MessageBox.Show("Close?", "Close window?", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                frm.Close();
            }
            else
            {
                frm.output.Text = (frm.output.Text + "\nClosing closed").ToString();
                frm.code.Clear();
            }
        }
        else
        {
            MessageBox.Show("test");
            frm.output.Text = (frm.output.Text + "\nI don't understand ... ").ToString();
            frm.code.Clear();
        } /**/

it only shows message box on end ....I think error is in declaring form1

Upvotes: 0

Views: 774

Answers (1)

Grant Winney
Grant Winney

Reputation: 66439

You have to pass a reference to the original Form, not create a new instance of it:

private new void Enter(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == Convert.ToChar(Keys.Enter))
    {
        Commands.OnCommand(this);



public static void OnCommand(Form1 frm)
{
    if (frm.code.Text.Contains("end") && frm.code.TextLength == 4)
    {

That being said, I'd consider it poor practice to send a reference to the entire Form into the other method. Instead, try to restructure it so that you pass in just those values the method needs (like code.Text), and have it return the values that the Form needs to display.

private new void Enter(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == Convert.ToChar(Keys.Enter))
    {
        string message = Commands.OnCommand(code.Text);

        if (message == "")
        {
            Close();
        }
        else
        {
            frm.output.Text = frm.output.Text + message;
            frm.code.Clear();
        }



public static void OnCommand(string code)
{
    if (code.Contains("end") && code.Length == 4)
    {
        if (MessageBox.Show("Close?", "Close window?", MessageBoxButtons.YesNo) == DialogResult.Yes)
            return "";
        else
            return "Closing closed";
    }
    else
    {
        MessageBox.Show("test");
        return "I don't understand ... ";
    }

Upvotes: 2

Related Questions