I'm currently stuck on creating a SQL Server database in Visual Studio. I went to server explorer, created a database called UserData.mdf
. Then I created a table to store usernames
and passwords
. I named the table LOGIN
and stored a username
called Faculty_ID
and a password
called pass123
I stored both as a Varchar(50)
datatype. Everything was fine until I had to write the code for my login button.
Here's the code snippet that is giving me an error:
SqlDataAdapter("Select Count (*) From dbo.[LOGIN] where Username='" + USERNAME_txt.Text + "' and Password ='" + password_txt.Text + "'", con);
where it says:
The name Username/password does not exist in the current context
What should I rename or change?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace LOGINPAGE
{
public partial class Room : Form
{
public Room()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
this.Hide();
FloorSelection ss = new FloorSelection();
ss.Show();
}
private void EXIT_Click(object sender, EventArgs e)
{
this.Close();
}
private void xButton1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mohamed\Documents\UserData.mdf;Integrated Security=True;Connect Timeout=30");
this.Hide();
SqlDataAdapter sda = new SqlDataAdapter("Select Count (*) From dbo.[LOGIN] where username='" + username_txt.Text + "' and Password ='" + password_txt.Text + "'", con);
FloorSelection ss = new FloorSelection();
ss.Show();
}
}
}
Would recommend always put the a forms values into variable and never reading them from the form directly into a query, even for tests, otherwise you end up with a very tightly coupled test.
Have you tried this approach?
void FillLogins(string userName, string password)
// Open connection
using (SqlConnection c = new SqlConnection(yourConnectionString))
{
c.Open();
// Create new DataAdapter / Command
using (SqlDataAdapter a = new SqlDataAdapter(
"Select Count (*) From dbo.[LOGIN] where Username= @userName AND Password = @password", c))
{
a.SelectCommand.Parameters.AddWithValue("@userName", userName);
a.SelectCommand.Parameters.AddWithValue("@password", password);
// Use DataAdapter to fill DataTable
DataTable t = new DataTable();
a.Fill(t);
}
}
}
Then you can call it like this (assuming you are not using databinding)
FillLogins(USERNAME_txt.Text, password_txt.Text);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.