用户登录经典代码

private void btnLogin_ServerClick(object sender, System.EventArgs e)
        
{
            SqlConnection con;
            
string sql;
            SqlCommand cmd;
            
string id;

            con 
= new SqlConnection("data source=(local)\\NetSdk;initial catalog=FriendsData;user id=sa");
            sql 
= "SELECT UserID FROM [User] WHERE Login='{0}' and Password='{1}'";
            
            
// Format the string with the values provided
            sql = String.Format(sql, txtLogin.Value, txtPwd.Value);
            cmd 
= new SqlCommand(sql, con);
            con.Open();

            
try 
            
{
                
// Retrieve the UserID
                id = (string) cmd.ExecuteScalar();
            }

            
finally 
            
{
                con.Close();
            }


            
if (id != null)
            
{
                
// Set the user as authenticated and send him to the page originally requested.
                FormsAuthentication.RedirectFromLoginPage(id, chkPersist.Checked);
            }

            
else
            
{
                
this.pnlError.Visible = true;
                
this.lblError.Text = "Invalid user name or password!";
            }

        }

原文地址:https://www.cnblogs.com/ahuang1118/p/172519.html