Slavik Ribz Slavik Ribz - 9 months ago 51
C# Question

Calling a function from another form c#

i have a main form with a function that changes the text of a text box thats on the main form, the code is below:

main form function:

public void consoleLog(string message)
{
txtConsoleLog.Text += Environment.NewLine;
txtConsoleLog.Text += message;
txtConsoleLog.SelectionStart = txtConsoleLog.TextLength;
txtConsoleLog.ScrollToCaret();
txtConsoleLog.Refresh();
}


So now i open a new form called frm connect when i click a button like this:

private void connectToolStripMenuItem_Click(object sender, EventArgs e)
{
Form frmConnect = new FrmConnect(this);
frmConnect.Show();
}


this is the frmConnect below

public partial class FrmConnect : Form
{
private Form mainForm;

public FrmConnect(Form frmMain)
{
this.mainForm = frmMain;
InitializeComponent();
}

private void btnConnect_Click(object sender, EventArgs e)
{
FrmMain.Connected = true;
mainForm.consoleLog("Connected");
}
}


So when i click a button i want to call the function but its saying it doesnt contain a definition for it, also im trying to change the 'Connected' variable thats on the main form which works by just referencing the FrmMain but am i able to do that using mainForm.Connected = true?

If i change the function to public static, it will work by referencing FrmMain but then i get errors with the txtConsoleLog as i cant reference an object in a non static method or something like that, any help is appriciated

Answer Source

You should change

private Form mainForm;

public FrmConnect(Form frmMain)
{

To

private FrmMain mainForm;

public FrmConnect(FrmMain frmMain)
{

which will later give you access to all of the public properties on FrmMain in your other methods in the FrmConnect class.