Reputation: 1
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Authenticator at = new Authenticator();
at.validate();
}
}
public class Authenticator
{
private int num;
public bool validate()
{
if (textBox1.Text == num.ToString()) // problem #1
{
ListBox.Items.Add("Valid"); // problem #2
}
}
}
}
Hello everyone.
As you can see from the above code I am writing an application that requires a user defined class to be able to access the winforms I am working with like in the above simplified example. I'm very new to C# so please forgive my ignorance.
I need the authenticator class to be able to access the data in a textbox and then compare it and if both strings are equal then update the listbox. Is there a simple way to do this?
Upvotes: 0
Views: 163
Reputation: 4006
Sorry I can't comment on your post, I don't have enough reputation.
I've had similar trouble once before getting a form to access a string from another form.
In my case I just had to make the string static. Try doing the same with your textbox.
public static TextBox textBox1;
public Form1()
Upvotes: 0
Reputation: 13533
Probably best to keep the gui separate from the logic:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Authenticator at = new Authenticator();
if (at.validate(textBox1.Text)) {
ListBox.Items.Add("Valid");
}
}
}
public class Authenticator
{
private int num;
public bool validate(string s)
{
if (s == num.ToString())
{
return true;
}
return false;
}
}
Upvotes: 3
Reputation: 10026
How about something like this?
public bool validate(string text)
{
return (text == num.ToString());
}
And calling it in your code like this. You should try to make code as reusable as possible. Which means that references to specific instances of controls on a Form is not always the best design.
if (at.validate(textBox1.Text))
{
ListBox.Items.Add("Valid");
}
Upvotes: 2