F How to create login using separate Class in C# | CodeTheta

How to create login using separate Class in C#

1. Create a folder within your project folder / solution.
2. Example : MainClasses. Within this folder create a class named CoreLIB.cs

Put the connectionString to your App.config file.
<?xml version="1.0" encoding="utf-8" ?>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
<add name="connstrng" connectionString="Data Source=.;Initial Catalog=database;Integrated Security=True;"/>

use Getter and Setter to CoreLIB.cs file.
public string Username { get; set; }
public string Password { get; set; }
static string myconnstrng = ConfigurationManager.ConnectionStrings["connstrng"].ConnectionString;

use following namespace system CoreLIB.cs file
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

Use login function
public bool Login(CoreLIB c)
            bool isSuccess = false;
            SqlConnection conn = new SqlConnection(myconnstrng);
            DataTable dt = new DataTable();
                string sql = "SELECT * FROM tablename WHERE Username=@Username AND Password=@Password";
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("@Username", c.Username);
                cmd.Parameters.AddWithValue("@Password", c.Password);
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);

                if(dt.Rows[0][0].ToString() == "1")
                    isSuccess = true;
                    isSuccess = false;

            catch(Exception ex)

            return isSuccess;

Login button code
use the following namespace system
using IJIRALIB.IJIRAClasses;
using System.Configuration;
using System.Data;

CoreLIB c = new CoreLIB();
private void btnLogin_Click(object sender, EventArgs e)
            c.Username = txtUsername.Text;
            c.Password = txtPassword.Text;
            bool success = c.Login(c);
                frmDashboard frm = new frmDashboard();
                MessageBox.Show("Invalid Login");

IDE Used To Test This Code : Visual Studio 2012.

Try this code in your computer for better understanding. Enjoy the code. If you have any Question you can contact us or mail us.We will reply you as soon as possible.

Post a Comment