December 31, 2016

Simple Login Application using Sessions in ASP.NET MVC

Continuation Form : Creating your first MVC Project

Step 1: Add Entity Data Model
Go to Solution Explorer, Right Click on Project, Add, New Item, then select ADO.NET Entity Data Model.


Give it a meaningful model name and then click on Add.


 Select Generate from database and then click on Next.

Click on New Connection,


After clicking on New Connection, we have to provide the required information

Click on the "Test Connection" button to ensure the connection can be established.
Then click OK. 

Select radio button: Yes include the sensitive data in the connection string.

Choose your database objects, as in the following image.


 Click on Finish. At this point UserProfie entity will be created.

December 17, 2016

Adding a Control to MVC Project

Continuation For :- Simple Login in MVC

Go to Solution Explorer, Right click on Controller folder, Add and then click on Controller.
( Or ) Simply use shortcut key Ctrl + M, Ctrl + C,

  
Provide the Controller Name, and Scaffolding template as LoginController. Then click on Add.


Write the following code in LoginController.


public class LoginController : Controller
    {
        //
        // GET: /Login/
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(M_USER objUser)
        {
            if (ModelState.IsValid)
            {
                using (SampleDataBaseEntities db = new SampleDataBaseEntities())
                {
                    var obj = db.M_USER.Where(a => a.USER_ID.Equals(objUser.USER_ID) && a.PASSWORD.Equals(objUser.PASSWORD)).FirstOrDefault();
                    if (obj != null)
                    {
                        Session["UserID"] = obj.USER_ID.ToString();
                        Session["UserName"] = obj.USER_NAME.ToString();
                        return RedirectToAction("UserDashBoard");
                    }
                }
            }
            return View(objUser);
        }

        public ActionResult UserDashBoard()
        {
            if (Session["UserID"] != null)
            {
                return View();
            }
            else
            {
                return RedirectToAction("Login");
            }
        }
 }

December 3, 2016

Creating View in MVC

Create View for Login Action Method
Right click on the Login Action method, then click on Add View as in the following picture.

Give a name for the View
Click Add.

 
 

November 24, 2016

November 18, 2016

November 16, 2016

November 4, 2016

November 3, 2016

October 19, 2016

October 6, 2016

clsExcel to xml class

 public class clsExcelToXML
    {
        #region Variable Declaration
        private OleDbConnection cn;
        private OleDbDataAdapter daAdapter;

        private string ExcelCon = @"Provider=Microsoft.Jet.OLEDB.4.0;";
        private string strConnectionString;

        private string strParseError = "";
        private string SheetName, Range;
        #endregion

        #region Constructors
        ///
        /// Initialize ExcelXML component using the sepecifed File name, By default HDR property will be false.
        ///

        ///
        public clsExcelToXML(string strFileName)
        {
            strConnectionString = ExcelCon + "Data Source=" + strFileName + ";Extended Properties=" + Convert.ToChar(34).ToString() + "Excel 8.0;HDR=No" + Convert.ToChar(34).ToString();
            cn = new OleDbConnection();
            cn.ConnectionString = strConnectionString;
        }

        ///
        /// Initialize ExcelXML component using the specified File name, you can specify HDR value using _blnHeaders
        ///

        ///
        ///
        public clsExcelToXML(string strFileName, Boolean _blnHeaders)
        {
            if (_blnHeaders)
                strConnectionString = ExcelCon + "Data Source=" + strFileName + ";Extended Properties=" + Convert.ToChar(34).ToString() + "Excel 8.0;HDR=Yes" + Convert.ToChar(34).ToString();
            else
                strConnectionString = ExcelCon + "Data Source=" + strFileName + ";Extended Properties=" + Convert.ToChar(34).ToString() + "Excel 8.0;HDR=No" + Convert.ToChar(34).ToString();

            cn = new OleDbConnection();
            cn.ConnectionString = strConnectionString;
        }

        #endregion

        #region Functionality

        #region XML Functionality
        public string GetXML(string strSheetName, Boolean _blnSchema)
        {
            DataSet ds = new DataSet();
            ds.Tables.Add(this.GetDataTable(strSheetName));

            if (_blnSchema)
                return ds.GetXmlSchema() + ds.GetXml();
            else
                return ds.GetXml();
        }
        public string GetXMLSchema(string strSheetName)
        {
            DataSet ds = new DataSet();
            ds.Tables.Add(this.GetDataTable(strSheetName));
            return ds.GetXmlSchema();
        }

        public string[] GetAllXML()
        {
            string[] excelSheet = GetExcelSheetNames();

            DataSet dsExcelData = new DataSet();
            DataTable dt = new DataTable();
            foreach (string strSheetName in excelSheet)
            {
                dsExcelData.Tables.Add(this.GetDataTable(strSheetName));
            }
            string[] xml = new string[2];
            xml[0] = dsExcelData.GetXmlSchema();
            xml[1] = dsExcelData.GetXml();
            return xml;
        }

        #endregion

        #region Excel File Info
        public String[] GetExcelSheetNames()
        {

            System.Data.DataTable dt = null;

            try
            {
                cn.Open();

                // Get the data table containing the schema
                dt = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

                if (dt == null)
                {
                    return null;
                }

                String[] excelSheets = new String[dt.Rows.Count];
                int i = 0;

                // Add the sheet name to the string array.
                foreach (DataRow row in dt.Rows)
                {

                    //string strSheetTableName = row["TABLE_NAME"].ToString();
                    string strSheetTableName = "Barcode Sequence$";
                    strSheetTableName.Trim(new char[] { '\\' });
                    excelSheets[i] = strSheetTableName.Substring(0, strSheetTableName.Length);
                    i++;
                }


                return excelSheets;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                // Clean up.
                cn.Close();
            }
        }
        public DataTable GetDataTableForCase(string strSheetName)
        {

            try
            {

                string strComand;
                if (strSheetName.IndexOf("|") > 0)
                {
                    SheetName = strSheetName.Substring(0, strSheetName.IndexOf("|"));
                    Range = strSheetName.Substring(strSheetName.IndexOf("|") + 1);
                    strComand = "select * from [" + SheetName + "$" + Range + "]";
                }
                else
                {
                    strSheetName = strSheetName.Substring(0, strSheetName.Length);
                    strComand = "select DISTINCT F5,F1 from [" + strSheetName + "]";


                }


                daAdapter = new OleDbDataAdapter(strComand, cn);
                DataTable dt = new DataTable(strSheetName);

                daAdapter.FillSchema(dt, SchemaType.Source);

                daAdapter.Fill(dt);
                dt.Rows.RemoveAt(0);
                cn.Close();

                 return dt;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
     
        public DataTable GetDataTable(string strSheetName)
        {

            try
            {

                string strComand;
                if (strSheetName.IndexOf("|") > 0)
                {
                    SheetName = strSheetName.Substring(0, strSheetName.IndexOf("|"));
                    Range = strSheetName.Substring(strSheetName.IndexOf("|") + 1);
                    strComand = "select * from [" + SheetName + "$" + Range + "]";
                }
                else
                {
                    strSheetName = strSheetName.Substring(0, strSheetName.Length);
                    strComand = "select * from [" + strSheetName + "]  " + " 'EXCEPT SELECT TOP 1 * from " + strSheetName + "'";


                }


                daAdapter = new OleDbDataAdapter(strComand, cn);
                DataTable dt = new DataTable(strSheetName);
               
                daAdapter.FillSchema(dt, SchemaType.Source);
               
                daAdapter.Fill(dt);
                dt.Rows.RemoveAt(0);
                cn.Close();

                return dt;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        #endregion

        #region Save Functionality
        public void SaveSheetXML(string strFileName, string strSheetName, Boolean _blnSchema)
        {
            try
            {
                string strFile = strFileName.Substring(strFileName.LastIndexOf("\\") + 1);
                string path = strFileName.Substring(0, strFileName.LastIndexOf("\\"));
                strFile = strFile.Remove(strFile.IndexOf("."), 4);
                SaveFile(path, strFile, strSheetName);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        private void SaveFile(string path, string strFile, string strSheetName)
        {
            FileStream file = new FileStream(path + "\\" + strFile + ".xml", FileMode.Create);
            StreamWriter wr = new StreamWriter(file);
            wr.Write("" + this.GetXML(strSheetName, false));
            wr.Close();
            file.Close();
            file = new FileStream(path + "\\" + strFile + ".xsd", FileMode.Create);
            wr = new StreamWriter(file);
            wr.Write(this.GetXMLSchema(strSheetName).Replace("utf-16", "utf-8"));
            wr.Close();
            file.Close();
        }
        public void SaveXslXml(string strFileName, Boolean _blnSchema, Boolean _blnMulti)
        {
            string[] excelSheet = GetExcelSheetNames();
            string strFile = strFileName.Substring(strFileName.LastIndexOf("\\") + 1);
            string path = strFileName.Substring(0, strFileName.LastIndexOf("\\"));
            strFile = strFile.Remove(strFile.IndexOf("."), 4);

            if (_blnMulti)
            {
                foreach (string strSheetName in excelSheet)
                {
                    this.SaveFile(path, strFile + "_" + strSheetName, strSheetName);

                }
            }
            else
            {
                string[] xml = this.GetAllXML();
                FileStream file = new FileStream(path + "\\" + strFile + ".xml", FileMode.Create);
                StreamWriter wr = new StreamWriter(file);
                wr.Write("" + xml[1]);
                wr.Close();
                file.Close();
                file = new FileStream(path + "\\" + strFile + ".xsd", FileMode.Create);
                wr = new StreamWriter(file);
                wr.Write(xml[0].Replace("utf-16", "utf-8"));
                wr.Close();
                file.Close();
            }

        }

        #endregion

        #region Validations
        public string ValidateXML(string strSchemaFile)
        {
            strParseError = "";

            XmlParserContext context = new XmlParserContext(null, new XmlNamespaceManager(new NameTable()), null, XmlSpace.None);
            XmlTextReader xmlReader = new XmlTextReader(this.GetAllXML()[1], XmlNodeType.Element, context);
            XmlValidatingReader objValidator = new XmlValidatingReader(xmlReader);

            //set the validation type to use an XSD schema
            objValidator.ValidationType = ValidationType.Schema;
            XmlSchemaCollection objSchemaCol = new XmlSchemaCollection();
            objSchemaCol.Add("", strSchemaFile);
            objValidator.Schemas.Add(objSchemaCol);
            objValidator.ValidationEventHandler += new ValidationEventHandler(ShowCompileErrors);

            try
            {
                while (objValidator.Read()) { }
                //xmlInfo.InnerHtml += "* XML was validated - " + intValidErrors + " error(s) found";
            }
            catch (Exception objError)
            {
                throw new Exception(objError.Message);
                //xmlInfo.InnerHtml += "* Read/Parser error: " + objError.Message + "
";
            }
            finally
            {
                xmlReader.Close();
            }
            return strParseError;
        }

        public string ValidateXML(string strSchemaFile, string WorkSheet)
        {

            strParseError = "";

            XmlParserContext context = new XmlParserContext(null, new XmlNamespaceManager(new NameTable()), null, XmlSpace.None);
            XmlTextReader xmlReader = new XmlTextReader(this.GetXML(WorkSheet, false), XmlNodeType.Element, context);
            XmlValidatingReader objValidator = new XmlValidatingReader(xmlReader);

            //set the validation type to use an XSD schema
            objValidator.ValidationType = ValidationType.Schema;
            XmlSchemaCollection objSchemaCol = new XmlSchemaCollection();
            objSchemaCol.Add("", strSchemaFile);
            objValidator.Schemas.Add(objSchemaCol);
            objValidator.ValidationEventHandler += new ValidationEventHandler(ShowCompileErrors);

            try
            {
                while (objValidator.Read()) { }
                //xmlInfo.InnerHtml += "* XML was validated - " + intValidErrors + " error(s) found";
            }
            catch (Exception objError)
            {
                throw new Exception(objError.Message);
                //xmlInfo.InnerHtml += "* Read/Parser error: " + objError.Message + "
";
            }
            finally
            {
                xmlReader.Close();
            }
            return strParseError;
        }

        private void ShowCompileErrors(object sender, ValidationEventArgs args)
        {
            strParseError += "::" + args.Message + "\r\n";
        }

        #endregion

        #region Batch Function
        public static void BatchXMLConvert(string[] Files, Boolean _blnMulti)
        {
            try
            {
                foreach (string FileName in Files)
                {
                    clsExcelToXML obj = new clsExcelToXML(FileName);
                    obj.SaveXslXml(FileName, true, _blnMulti);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        #endregion

        #endregion


     
    }

Excel to xml Conversion

public partial class frmXmlConversion : Form
    {
        private string strFileName;
        private clsExcelToXML obj;
        private string strSheetNameRange;
        private DataSet dsFile;
        string filepath;
        string Newxmlfilename;
        string fileNameWithoutex;

        public frmXmlConversion()
        {
            InitializeComponent();
        }

        private void frmXmlConversion_Load(object sender, EventArgs e)
        {
            this.FormBorderStyle = FormBorderStyle.None;
            this.Activate();
            Application.DoEvents();
        }

        private void frmXmlConversion_Activated(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Maximized;
            this.FormBorderStyle = FormBorderStyle.None;
        }

        private void btnBro_Click(object sender, EventArgs e)
        {
            try
            {
                dlgOpenFile.Filter = "Excel File(*.xls)|*.xls";
                dlgOpenFile.ShowDialog();
                strFileName = dlgOpenFile.FileName;
                obj = new clsExcelToXML(strFileName, false);
                txtFileName.Text = strFileName;
                string[] sheetnames = obj.GetExcelSheetNames();
                cboSheetName.Items.Clear();
                cboSheetName.Items.AddRange(sheetnames);
                cboSheetName.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnConvert_Click(object sender, EventArgs e)
        {
            CreateXmlForBarcode();
            CreateXmlForCase();
        }

        private void CreateXmlForCase()
        {
            try
            {
                dsFile = new DataSet();
                DataTable dt = new DataTable();
                strSheetNameRange = cboSheetName.Text.ToString();

                dt = obj.GetDataTable(strSheetNameRange);

                if (dt.Rows.Count > 0)
                {
                    XmlWriterSettings contentTypesSettings = new XmlWriterSettings();
                    contentTypesSettings.Indent = true;

                    filepath = txtFileName.Text;
                    fileNameWithoutex = Path.Combine(Path.GetDirectoryName(filepath), Path.GetFileNameWithoutExtension(filepath));
                    Newxmlfilename = fileNameWithoutex + "_Case.xml";
                    XmlWriter xmlWriter = XmlWriter.Create(Newxmlfilename);

                    xmlWriter.WriteStartDocument(true);
                    xmlWriter.WriteStartElement("UNMAPPED_DATASET");

                    string chk = string.Empty;
                    foreach (DataRow dr in dt.Rows)
                    {
                        if (chk != dr["F1"].ToString())
                        {
                            if (chk != string.Empty)
                                chk = dr["F1"].ToString();

                            xmlWriter.WriteStartElement("CASE");
                            xmlWriter.WriteAttributeString("GTIN", dr["F1"].ToString());
                            xmlWriter.WriteAttributeString("ETN", dr["F5"].ToString());
                            xmlWriter.WriteEndElement();
                        }
                    }
                    if (xmlWriter != null)
                        xmlWriter.Flush();

                    xmlWriter.Close();

                }
                Functions.setMessageBox(Functions.gApp, "Both files exported Sucessfully", 1);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void CreateXmlForBarcode()
        {
            try
            {
                dsFile = new DataSet();
                DataTable dt = new DataTable();
                strSheetNameRange = cboSheetName.Text.ToString();

                dt = obj.GetDataTable(strSheetNameRange);

                if (dt.Rows.Count > 0)
                {
                    XmlWriterSettings contentTypesSettings = new XmlWriterSettings();
                    contentTypesSettings.Indent = true;

                    filepath = txtFileName.Text;
                    fileNameWithoutex = Path.Combine(Path.GetDirectoryName(filepath), Path.GetFileNameWithoutExtension(filepath));
                    Newxmlfilename = fileNameWithoutex + "_Barcode.xml";
                    XmlWriter xmlWriter = XmlWriter.Create(Newxmlfilename);

                    xmlWriter.WriteStartDocument(true);
                    xmlWriter.WriteStartElement("UNMAPPED_DATASET");
                   
                    string chk = string.Empty;
                    foreach (DataRow dr in dt.Rows)
                    {
                        if (chk != dr["F6"].ToString())
                        {
                            if (chk != string.Empty)
                            chk = dr["F6"].ToString();
                          
                            xmlWriter.WriteStartElement("BOTTLE");
                            xmlWriter.WriteAttributeString("BARCODE", dr["F6"].ToString());
                            xmlWriter.WriteEndElement();
                        }
                    }
                    if (xmlWriter != null)
                        xmlWriter.Flush();

                    xmlWriter.Close();

                }
              
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }

September 17, 2016

Insert checked rows records of datagridview into database

 dataGridView1.AllowUserToAddRows = false;
            dataGridView1.Columns.Clear();
            DataGridViewCheckBoxColumn col1 = new DataGridViewCheckBoxColumn();
            col1.Name = "chkcol";
            col1.HeaderText = "SELECT";
          
            dataGridView1.Columns.Add(col1);
            setReload();
            dataGridView1.Columns[1].HeaderText = "ATTEMPT NO";
            dataGridView1.Columns[2].HeaderText = "CAMERA 1";
            dataGridView1.Columns[3].HeaderText = "CAMERA 2";
            foreach (DataGridViewColumn col in dataGridView1.Columns)
            {
                col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                col.HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Bold, GraphicsUnit.Pixel);
            }


 private void btnAdd_Click(object sender, EventArgs e)
        {
            int i = 0;
            List ChkedRow = new List();
            for (i = 0; i <= dataGridView1.RowCount - 1; i++)
            {
                if (Convert.ToBoolean(dataGridView1.Rows[i].Cells["chkcol"].Value) == true)
                {
                    ChkedRow.Add(i);
                }
            }
            if (ChkedRow.Count == 0)
            {
                MessageBox.Show("Plase select the attempt numbers.");
                return;
            }
            for (i = 0; i <= dataGridView1.RowCount - 1; i++)
            {
                if (Convert.ToBoolean(dataGridView1.Rows[i].Cells["chkcol"].Value) == true)
                {
                    ChkedRow.Add(i);
                }
            }

            string str;
            foreach (int j in ChkedRow)
            {
                str = @"update Tbl_Camera_configuration set camera_1 = '" + dataGridView1.Rows[j].Cells["Camera_1"].Value + "', Camera_2 = '" + dataGridView1.Rows[j].Cells["Camera_2"].Value + "' where Attempt_No = '" + dataGridView1.Rows[j].Cells["Attempt_No"].Value + "'";
                try
                {
                    using (SqlConnection con = new SqlConnection(constring))
                    {
                        using (SqlCommand cmd = new SqlCommand(str, con))
                        {
                            con.Open();
                            cmd.ExecuteNonQuery();
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            MessageBox.Show("Records updated sucessfully");
        }

Changing DataGridView Header Cells' Text Alignment And The Font Size

foreach(DataGridViewColumn col in dgvBreakDowns.Columns)
{
    col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
    col.HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Bold, GraphicsUnit.Pixel);
}

September 15, 2016

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

Request.Redirect(url,false);
false indicates whether execution of current page should terminate.

Server.MapPath does not exist in the Current Context

System.Web.HttpContext.Current.Server.MapPath()
 
import system.web


 

August 17, 2016

August 15, 2016

August 6, 2016

May 28, 2016

Text Box Should Only Accept Numeric Values


 Hi Friends,

Today I will tell you how a Text Box Will only accept Numeric Values

private void txtPayment_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }

Hope that this simple code will make your work done.

Regards
Sudhir Singh
Software Developer at Fadsan Technologies
  



          

        


March 19, 2016

Message Box in C#

We can call MessageBox.Show with just one argument. This is a string argument. An OK button is provided to dismiss the dialog.

MessageBox.Show("Welcome to askSudhir.");


Now let's add a second argument to our Show method call. The second argument is also a string. Sorry about the silly dialog text.

  MessageBox.Show("Welcome to askSudhir","Hi this is the header");


I like icons. Here we use an exclamation on our dialog. We specify MessageBoxIcon.Exclamation in the fourth method call. Again sorry for the message text.


March 18, 2016

International Scores

Email Validation in Windows Application C#.Net 

Today email is have becomes most important part of our life. So whenever we are developing any application in either in windows or web ad asking user for email id of user, so before saving the data we must validate that email id entered by user must be valid.

So in this article I will show you how you can validate the email id in a windows application using C#.Net  
 
 
private void txtUserName_Validating(object sender, CancelEventArgs e)
        {
            System.Text.RegularExpressions.Regex rEMail = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z][\w\.-]{2,28}[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$");
            if (txtUserName.Text.Length > 0)
            {
                if (!rEMail.IsMatch(txtUserName.Text))
                {
                    MessageBox.Show("E-Mail expected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtUserName.SelectAll();
                    e.Cancel = true;
                }
            }
          
        }

 


Tommarow is the great match


March 15, 2016

India Started its world Cup T20 Journey today

T20 Cricket world cup 2016 (IND VS NZ)

India

Shikhar Dhawan, Rohit Sharma, Virat Kohli, Ajinkya Rahane, MS Dhoni, Yuvraj Singh, Suresh Raina, Ravindra Jadeja, Ravichandran Ashwin, Pawan Negi, Mohammed Shami, Ashish Nehra, Jasprit Bumrah, Harbhajan Singh, Hardik Pandya


New Zealand

Kane Williamson, Martin Guptill, Trent Boult, Nathan McCullum, Colin Munro, Luke Ronchi, Ish Sodhi, Ross Taylor, Corey Anderson, Grant Elliott, Mitchell McClenaghan, Adam Milne, Henry Nicholls, Mitchell Santner, Tim Southee


March 3, 2016

gdfg



DateTime dateAndTime = DateTime.Now;
Console.WriteLine(dateAndTime.ToString("dd/MM/yyyy")); // Will give you smth like 25/05/2011
  1. vc
  2. vcxvxcvxcv
  3. vxcvxvcxvxvcvcvcxv
  4. vxvxvcxv    

March 2, 2016

How to delete the top 30 rows from a table using Sql Server

For those wondering why you can't do DELETE TOP (30) FROM table ORDER BY column, the answer is

 "The rows referenced in the TOP expression used with INSERT, UPDATE, MERGE, or DELETE are not arranged in any order."

For a specific ordering criteria deleting from a CTE or similar table expression is the most efficient way.
;WITH CTE AS
(
SELECT TOP 30 *
FROM [My_Table]
ORDER BY a1
)
DELETE FROM CTE

Login Page in C#.Net Using Stored Procedure

I have often read forum posts asking how to create the login page using a Stored Procedure. So by considering the above requirement I have decided to write this article to help beginners, students and who wants to learn how to create a Login page using a Stored Procedure.

walk-through


Step -1 : Create a table


CREATE TABLE [dbo].[Login] ( [UserName] NVARCHAR (50) NULL, [Password] NVARCHAR (50) NULL, [SecurityQuestion] NVARCHAR (MAX) NULL, [SecurityAnswer] NVARCHAR (MAX) NULL );

Step -2 : Now let us create a Stored Procedure named sp_Validateuser as follows:

CREATE PROCEDURE sp_ValidateUser ( @User_name VARCHAR(50) ,@User_password VARCHAR(50) ) AS BEGIN SELECT UserName ,Password FROM Login_Details WHERE UserName=@User_name AND Password=@User_password END

Step -3 : Create a Login Form

Write the following code in the Button1_click function as:

if (txtUserName.Text == "") { MessageBox.Show("Please enter the user name", "OOPPS", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else if (txtPwd.Text == "") { MessageBox.Show("Please enter the password", "OOPPS", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { DataTable dt = new DataTable(); SqlDataAdapter adp = new SqlDataAdapter(); try { SqlCommand cmd = new SqlCommand("sp_ValidateUser", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@User_name ", txtUserName.Text.Trim()); cmd.Parameters.AddWithValue("@User_password ", txtPwd.Text.Trim()); adp.SelectCommand = cmd; adp.Fill(dt); cmd.Dispose(); if (dt.Rows.Count > 0) { // Perform the action if username and password is correct } else { MessageBox.Show("User Name or Password is wrong", "Please check", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); txtUserName.Text = ""; txtPwd.Text = ""; txtUserName.Focus(); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { dt.Clear(); dt.Dispose(); adp.Dispose(); } }