...

View Full Version : [C#] how to create a function within a class



Scientist_nl
10-25-2007, 10:40 PM
Hi guys,

I need to store a function in a class, which can be accessed all the time. For instance: a user types his name in a messagebox, clicks the OK-button, and a new form will show. There is a new button on the second form, which needs to trigger the class function where a popup-box is generated which will show a welcome-message with the user's name. How do I need to program this? And how do I close the first form after showing the second?

Thanks in advance!

Edit: getting a bit further. Got the function inside the class working, now I need to create a variable which saves the info from the messagebox in the form. This is my code, and this is as far as I can get:

Form1.cs


public void button1_Click(object sender, EventArgs e)
{
Class1.test();
}


Class1.cs


public static void test()
{
string test123 = txtTest.Text;
Form testform1 = new Form1();
Form testform2 = new Form2();
testform2.Show();
testform.close(); // How to close the first form??
}


Form2.cs


private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(test123);
}


Anyone knows how to solve this?

Roelf
10-26-2007, 01:58 PM
In the code for Form2, you can have a property. Set it after you create an instance of your form

From2.cs:
add:

// declare field
public string msgtext

//declare property
public string msgtext
{
get
{
return msgtext;
}
set
{
msgtext = value;
}
}
change:

private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(msgtext);
}


class1.cs:
change

public static void test()
{
string test123 = txtTest.Text;
Form testform1 = new Form1();
Form testform2 = new Form2();
testform2.msgtext = txtTest.Text;
testform2.Show();
testform.close(); // How to close the first form??
}

Scientist_nl
10-26-2007, 02:50 PM
didn't do the trick :( For some reason he can't find the object txtTest, which is created in Form1.cs, in Class1.cs :(



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum