Mark Nartea
Mark Nartea

Reputation: 67

How to access an object from a form to another class in c#.net

I have a form named frmMain.cs that contains two(2) text boxes, txtUsername, and txtPassword, I want to access them in the class that I created named CheckIfUsernameAndPasswordExist.cs please note that the two objects modifier is in public already. when I use the correct class name of frmMain.cs the error says that "An object reference is required for the non-static field, method or property" so I create a new instance of that class "frmMain formMain = new frmMain();" but the problem when I run my program those objects are empty so that it cannot access my database values. please help me, thank you. I'm a newbie in C#.

frmMain formMain = new frmMain();
cmd.Parameters.AddWithValue("@user", formMain.txtUsername.Text );
cmd.Parameters.AddWithValue("@pass", formMain.txtPassword.Text);

Upvotes: 1

Views: 78

Answers (2)

Vashdev Heerani
Vashdev Heerani

Reputation: 679

Create new frmMain will give you completely new object with all its variable as a default initialized what you need to do is to create new static class that store username and password and use them in your code

Upvotes: 0

user11722267
user11722267

Reputation:

Well, the most practical way is to simply pass the values of txtUsername.Text and txtPassword.Text to your Authentication.cs class (or in your case is called CheckIfUsernameAndPasswordExist.cs) after the user presses the Submit button.

private void btnSubmit_Click(object sender, EventArgs e)
{
    bool blnRes = Authentication.Authenicate(txtUsername.Text.Trim(),
                                             txtPassword.Text.Trim());
}

Upvotes: 2

Related Questions