CS0103 The name 'txtUserName' does not exist in the current context Im Having This Error How Can I Stop It

snaiper rex 1 Reputation point
2021-12-16T09:12:05.95+00:00

I want to connect My Project To SQL Using this Method But It doesn't Compile

        SqlConnection Con = new SqlConnection("Data Source= DARKHUNTER; Database= FirstProject; Integrated security = true ");

        Con.Open();

        SqlCommand cmd = new SqlCommand("select * From Accunts Where Username = '" + txtUserName.Text + "'And Password = '" + txtPassWord.Text + "'". Con);
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,675 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Ken Tucker 5,846 Reputation points
    2021-12-23T12:18:11.46+00:00

    This line of code is a security issue.

      SqlCommand cmd = new SqlCommand("select * From Accunts Where Username = '" + txtUserName.Text + "'And Password = '" + txtPassWord.Text + "'". Con);
    

    It opens you up to Sql injection. Someone could enter ' or 1=1 -- into the txtUserName and be able to log in

    Use SQL parameters to prevent this

    SqlCommand cmd = new SqlCommand("select * From Accunts Where Username = @UserName'And Password =@Password". Con);
    cmd.Parameters.AddWithValue("@UserName",txtUserName.Text);
    cmd.Parameters.AddWithValue("@Password", txtPassWord.Text);
    
    0 comments No comments