C# Exercises

Home AgriMetSoft About Contact

How to Create Login Form in WinForms

	    
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Login_Form_in_Winforms
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      this.Close();
    }

    private void login_button_Click(object sender, EventArgs e)
    {
      SqlConnection cnn = new SqlConnection(@"Data Source=DESKTOP-J9K51EL\AMSSQL;Initial Catalog=Database1;Integrated Security=True");
      string query = string.Format(@"Select count(*) from users where user='{0}' and pass='{1}'", user.Text, password.Text);
      SqlCommand command = new SqlCommand("SELECT Count(*) FROM users WHERE USERNAME = @u AND PASSWORD = @p", cnn);
      // Add the parameters for the SelectCommand.
      command.Parameters.AddWithValue("@u", user.Text);
      command.Parameters.AddWithValue("@p", password.Text);    
      SqlDataAdapter da = new SqlDataAdapter(command);

      DataTable dt = new DataTable();
      da.Fill(dt);
      cnn.Close();
      if (dt.Rows[0][0].ToString() == "1")
      {
        new MainForm().Show();
        this.Hide();
      }
      else
      { MessageBox.Show("Check the Username or Password!"); }
    }
  }
}

		
	 


Download the project of Visual Studio 2013 in DropBox Download


How to Create Login Form in C# WinForms with SQL Server Database


List of Exercises