Click here to Skip to main content
15,881,852 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This is Vs2010 C# project
I am totally newbie at C#, I'm Creating a School Project and
I am currently need a Log-in function on my Program

All the tutorials at the net keeps me puzzled

WPF project
Textbox (textBox1)
Passwordbox (passwordbox1)
service-based database (Database1.mdf) what is the best setting for database
textblock (textBlock5)for error

C#
private void Button1_Click(object sender, RoutedEventArgs e)
       {
           string UserId = textBox1.Text;
           string Password = passwordbox1.Password;
           SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True");
   conn.Open();
   SqlCommand cmd = new SqlCommand("Select * from Login where UserId#='" + UserId + "' and Password='" + Password + "'", conn);
   cmd.CommandType = CommandType.Text;
   SqlDataAdapter adapter = new SqlDataAdapter();
   adapter.SelectCommand = cmd;
   DataSet dataSet = new DataSet();
   adapter.Fill(dataSet);
          if (dataSet.Tables[0].Rows.Count>0)
           {
              string username = dataSet.Tables[0].Rows[0]["UserId#"].ToString() + "" +
                  dataSet.Tables[0].Rows[0]["Password"].ToString();
              this.Hide();
              Form MainWindow = new Form();
              MainWindow.Show();
              this.Close();
           }

           else
              if (textBox1.Text.Length == 0)
              {
                  textBlock5.Visibility = System.Windows.Visibility.Visible;
              }
           else
           {
               textBlock5.Visibility = System.Windows.Visibility.Visible;
               conn.Close();
           }

       }
Posted
Updated 31-Jul-14 6:13am
v2

1 solution

Hi there,
Its very easy to create a Login Form with C# and WPF.

I just created it. You can keep Connection String in project settings. For this,
1. You need to right click on your wpf project and select Properties.
2. There you will find a tab named "Settings" next to "Services" and followed by "Reference Paths". Now Click on that - Settings.
3. Now you can add Name for your setting and You can also set type i.e., datatype and Scope for your setting. Keep Scope to User, and provide value for your setting,
i.e., your connection string "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True".
4. Save the project now.

Now talking about WPF Login project, I create a WPF window with
TextBox for Username
PasswordBox for Password
TextBlock for Error
Buttons for Login, Reset the input fields and closing the window.

And I created a seperate class file named "Authorization.cs" to keep Login function seperate from code behind window file. In Autorization class, I created a function called Login(string Username, string Password), which needs two string parameters for passing username and password.

And I paste the code for the project,

For MainWindow.xaml

XML
<window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d" x:Class="LoginExample.MainWindow"
        Title="User Login" Height="212" Width="400">
    <grid>
    	<groupbox x:name="GroupBoxLogin" header="Login Form" margin="8" xmlns:x="#unknown">
    		<grid>
    			<label x:name="LabelUserName" content="User Name:" horizontalalignment="Left" verticalalignment="Top" margin="8,8,0,0" width="115.993" />
    			<label x:name="LabelPassword" content="Password:" horizontalalignment="Left" verticalalignment="Top" margin="8,37.96,0,0" width="115.993" />
    			<textbox x:name="TextUserName" textwrapping="Wrap" verticalalignment="Top" margin="123.993,8,8,0" height="25.96" />
    			<passwordbox x:name="PasswordUserPwd" verticalalignment="Top" margin="123.993,37.96,8,0" height="25.96" />
    			<textblock x:name="TextError" textwrapping="Wrap" verticalalignment="Top" margin="123.993,67.92,8,0" height="21.96" foreground="Red" fontstyle="Italic" />
    			<button x:name="ButtonLogIn" content="Log In" horizontalalignment="Left" width="100" margin="8.993,93.88,0,0" verticalalignment="Top" height="30" click="Button_Click" />
    			<button x:name="ButtonReset" content="Reset" margin="0,93.88,0,0" height="30" verticalalignment="Top" click="Button_Click" width="100" horizontalalignment="Center" />
    			<button x:name="ButtonCancel" content="Cancel" margin="0,93.88,8,0" height="30" verticalalignment="Top" click="Button_Click" horizontalalignment="Right" width="100" />
    		</grid>
    	</groupbox>
    </grid>
</window>



For MainWindow.xaml.cs

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace LoginExample
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            try
            {
                if (sender == ButtonLogIn)
                {
                    if (Authorization.Login(TextUserName.Text.Trim(), PasswordUserPwd.Password.Trim()) == true)
                    {
                        MessageBox.Show("Login Successfull");
                        // You can now open your main form here
                    }
                    else
                    {
                        TextError.Text = "* Username or Password is incorrect.";
                    }
                }

                if (sender == ButtonReset)
                {
                    TextUserName.Text = "";
                    PasswordUserPwd.Password = "";
                    TextError.Text = "";
                }

                if (sender == ButtonCancel)
                {
                    this.Close();
                }
            }
            catch (Exception Ex)
            {
                MessageBox.Show("Exception: " + Ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }
}


For Class Autorization.cs

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace LoginExample
{
    public static class Authorization
    {
        public static bool Login(string UserName, string Password)
        {
            DataTable _DataTable = new DataTable();
            SqlConnection _SqlConnection = new SqlConnection(Properties.Settings.Default.ConnectionString);
            _SqlConnection.Open();

            using (SqlDataAdapter _SqlDataAdapter = new SqlDataAdapter("SELECT * FROM Login WHERE UserId#='" + UserName + "' AND Password='" + Password + "'", _SqlConnection))
            {
                _SqlDataAdapter.Fill(_DataTable);
            }

            if (_DataTable.Rows.Count != 0)
                return true;
            else
                return false;
        }
    }
}


Here MainWindow refers your Login Window.
 
Share this answer
 
v2
Comments
Member 10973822 8-Aug-14 6:08am    
Thank you very much! VRKarthikeyan, I understand everything, it really works now :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900