Click here to Skip to main content
15,918,404 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi friends,

Can you help me to correct this code


private void button1_Click(object sender, EventArgs e)
       {
           string constring;
           constring = "Server=NGENIOUS-WSSDEV\\SQLEXPRESS;Database=MIC;Trusted_Connection= True";
           SqlConnection dbcon = new SqlConnection(constring);
           frmlogin = this.txtusername.Text;
           string strpassword = this.txtpassword.Text;
           if(frmlogin = null |= strpassword=null)
           {
               MessageBox.Show("You are Missing information. Please make sure that both the username and password fields are filled out.","Missing Info");
               this.txtusername.Focus();
               return;
           }
           string strsql = "select username, password from login";
           SqlCommand cm = new SqlCommand(strsql,dbcon);
           SqlDataReader dr;
           Boolean valid = false;
           Boolean hasrows = false;
           try
           {
               dbcon.Open();
               dr = cm.ExecuteReader();
               if(dr.HasRows)
               {
                   while (dr.Read())
                       if(strpassword == dr.item("password"))
                       {
                           valid=true;
                       }
                   hasrows=true;
               }
               dr.Close();
           }
           catch(Exception exo)
           {
               if(dbcon.State==ConnectionState.Open)
               {
                   dbcon.Close();
               }
               cm=null;
               dr = null;
               dbcon.Dispose();
               GC.Collect();
           }
           icount = icount +1;
           if(valid==true)
           {
               this.Hide();
               frmlogin.show();
           }
           else
               if(hasrows==false)
               {
                   MessageBox.Show("Invalid username & Password, Try Again!","Invalid Info");
                   this.txtusername.Focus();
                   //this.txtpassword.Focus();
                   this.txtusername.Text="";
                   this.txtpassword.Text="";
               }
               else
               {
                   MessageBox.Show("Invalid password, Try again!","Invalid Info");
                   this.txtpassword.Focus();
                   this.txtpassword.Text="";
               }





Thanks in advance
Posted
Updated 30-Nov-10 1:52am
v4
Comments
aayu 22-Nov-10 6:27am    
@Dalek Dave can you please let me know y u have locked my question??????????
Dalek Dave 22-Nov-10 6:28am    
Edited for Grammar and Readability.
Ankur\m/ 22-Nov-10 6:28am    
Don't worry. He is editing your question and edit notes will be available to you.
Dalek Dave 22-Nov-10 6:29am    
It locks Question whilst someone is editing, it should be unlocked now.
fjdiewornncalwe 30-Nov-10 7:56am    
Just as a suggestion: You are sending passwords in plain text in this code. If your final production release is going to be accessing a centralized sql server, then you may wish to look into some password encryption. :)

OMFG dont use
"WHERE username = '" + frmUsername.Text + "' AND password = '" + frmPassword.Text + "'";

This is straight path to SQL injection, i can execute any request here, like typing in login textbox something like this -

somelogin "" select 1 --

and i will login without password and login

Also use Form authentification with MembershipProvider class this should be a rite way for me.
 
Share this answer
 
v2
This is new answer:
add following code block in you Login page
C#
int cntUser = DBHelper.DB.ExecuteScalar("SELECT COUNT (*) FROM [signin] WHERE username='" + txtusername.Text + "' AND password='" + txtpassword.Text + "'");
if (cntUser > 0)
{
    frmMain main = new frmMain();
    main.Show();
}
else
{
    MessageBox.Show("Invalid User Name or Password");
}


add new class file "clsDBHelper.cs" in your solution
C#
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.IO;
using System.Windows.Forms;
using System.Data.OleDb;
namespace DBHelper
{
    public sealed class DB
    {
        //You need to verify following connection string
        const string DBConnection = "Server=NGENIOUS-WSSDEV\SQLEXPRESS;Database=MIC;Trusted_Connection= True";
        private DB()
        {
        }
        public static OleDbDataReader getDataReader(string strsql)
        {
            try
            {
                OleDbConnection con = new OleDbConnection();
                con = getConnection();
                OleDbCommand cmd = new OleDbCommand(strsql, con);
                OleDbDataReader dr = cmd.ExecuteReader();
                return dr;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Sorry! for inconvenience.\nPlease report following error to imdadhusen.sunasara@gmail.com, If you can see more than once.\n" + ex.Message, "Database Error", MessageBoxButtons.OK);
            }
            return null;
        }
        public static DataTable getDataTable(string strsql)
        {
            try
            {
                OleDbConnection con = new OleDbConnection();
                con = getConnection();
                OleDbDataAdapter da = new OleDbDataAdapter(strsql, con);
                DataSet ds = new DataSet();
                da.Fill(ds);
                //closeConnection(con);
                return ds.Tables[0];
            }
            catch (Exception ex)
            {
                MessageBox.Show("Sorry! for inconvenience.\nPlease report following error to imdadhusen.sunasara@gmail.com, If you can see more than once.\n" + ex.Message, "Database Error", MessageBoxButtons.OK);
            }
            return null;
        }
        public static int ExecuteNonQuery(string strsql)
        {
            int isSuccess = 0;
            try
            {
                OleDbConnection con = new OleDbConnection();
                con = getConnection();
                OleDbCommand cmd = con.CreateCommand();
                cmd.CommandText = strsql;
                isSuccess = cmd.ExecuteNonQuery();
                closeConnection(con);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Sorry! for inconvenience.\nPlease report following error to imdadhusen.sunasara@gmail.com, If you can see more than once.\n" + ex.Message, "Database Error", MessageBoxButtons.OK);
            }
            return isSuccess;
        }
        public static int ExecuteScalar(string strsql)
        {
            int isSuccess = 0;
            OleDbConnection con = new OleDbConnection();
            con = getConnection();
            OleDbCommand cmd = con.CreateCommand();
            cmd.CommandText = strsql;
            try
            {
                isSuccess = Convert.ToInt32(cmd.ExecuteScalar());
            }
            catch
            {
                isSuccess = 0;
            }
            closeConnection(con);
            return isSuccess;
        }
        public static OleDbConnection getConnection()
        {
            OleDbConnection con = new OleDbConnection();
            try
            {
                string MDBFilePath = Environment.GetFolderPath(Environment.SpecialFolder.System) + "\\SBSysDB.mdb";
                string strcon = DBConnection.Replace("{0}", MDBFilePath);
                con = new OleDbConnection(strcon);
                if (con.State != ConnectionState.Open) con.Open();
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                MessageBox.Show("Sorry! for inconvenience.\nPlease report following error to imdadhusen.sunasara@gmail.com, If you can see more than once.\n" + ex.Message, "Database Error", MessageBoxButtons.OK);
            }
            return con;
        }
        public static void closeConnection(OleDbConnection con)
        {
            if (con.State == ConnectionState.Open) con.Close();
        }
    }
}


Please use the above solution and it will working fine.


Please do let me know, if you have any doubt.

Please provide "Vote":thumbsup: if this would be helpful, and make "Accept Answer" if this would be correct answer.:rose:

Thanks,
Imdadhusen
 
Share this answer
 
Comments
Sunasara Imdadhusen 22-Nov-10 7:34am    
You need to slight modification for OLEDB to SQL
Replace To
OleDbDataReader SqlDataReader
OleDbConnection SqlConnection
OleDbCommand SqlCommand
OleDbDataAdapter SqlDataAdapter
Sunasara Imdadhusen 22-Nov-10 7:37am    
Also update following function for connection
public static SqlConnection getConnection()
{
SqlConnection con = new SqlConnection();
try
{
con.ConnectionString = DBConnection;
if (con.State != ConnectionState.Open) con.Open();
}
catch (Exception ex)
{
MessageBox.Show("Sorry! for inconvenience.\nPlease report following error to imdadhusen.sunasara@gmail.com, If you can see more than once.\n" + ex.Message, "Database Error", MessageBoxButtons.OK);
}
return con;
}
public static void closeConnection(SqlConnection con)
{
if (con.State == ConnectionState.Open) con.Close();
}
Hi Arti,

Updated Answer:

VB
string selectString =
"SELECT COUNT (*) " +
"FROM forum_members " +
"WHERE username = '" + frmUsername.Text + "' AND password = '" + frmPassword.Text + "'";



You don't want to change IF condition because it's already check.

this statement if (strResult.Length == 0) is return 0 if user name or password dose not match else 1.

Example:
C#
if (strResult.Length == 0)
{
    frmMain main = new frmMain();
    main.Show();
}
else
{
    MessageBox.Show("Invalid User Name or Password");
}


Please do let me know, if you have any doubt.

Please provide "Vote":thumbsup: if this would be helpful, and make "Accept Answer" if this would be correct answer.:rose:

Thanks,
Imdadhusen
 
Share this answer
 
v4
Comments
aayu 22-Nov-10 6:28am    
@Sunasara the code which i have mention is from goolge and i don't want in this form so please help me if there is any other way
Dalek Dave 22-Nov-10 6:28am    
Good Call.
Sunasara Imdadhusen 22-Nov-10 6:29am    
What you mean to say?
Sunasara Imdadhusen 22-Nov-10 6:39am    
Do you have any doubt? please feel free to ask me.
aayu 22-Nov-10 6:41am    
This code is written by me and i am getting error
(ExecuteScalar: Connection property has not been initialized.)

private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Server=NGENIOUS-WSSDEV\SQLEXPRESS;Database=MIC;Trusted_Connection= True");


SqlCommand cmd = new SqlCommand("select username,password" + "from signin" + "where username='" + txtusername.Text + "','" + txtpassword.Text + "'");
//cmd.ExecuteNonQuery();
con.Open();
string str = string.Empty;
str=(string)cmd.ExecuteScalar();
con.Close();
if (str.Length==0)
{
MessageBox.Show("Access denied");
}
else
{
MessageBox.Show("Access Granted ");
}

}

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