SqlException was Unhandled - c#

I'm trying to make a log in form in c# with database i don't know what to do and it is the code the error said the SQLException was Unhandled on the part of sda.Fill(dt) here is the code
SqlConnection con = new SqlConnection(#"Data Source=.\LOUI;Initial Catalog=login_db;User ID=sa;Password=1029384756");
SqlDataAdapter sda = new SqlDataAdapter("Select Count (*) From login_tbl where username = '" + User_txt.Text + "'and password = '" +Pass_txt.Text+ "'",con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
this.Hide();
adminpanel ap = new adminpanel();
ap.Show();
}
else
{
MessageBox.Show("Check Username or Password");
}

Replace sda.Fill(dt); with
try
{
sda.Fill(dt);
}
catch (SQLException ex)
{
Console.WriteLine(ex.ToString());
}
and edit your question to include the new output.

try
{
SqlConnection con = new SqlConnection(#"Data Source=.\LOUI;InitialCatalog=login_db;User ID=sa;Password=1029384756");//problem is here
SqlDataAdapter sda = new SqlDataAdapter("Select Count (*) From login where name = '" + User_txt.Text + "'and pass = '" + Pass_txt.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
this.Hide();
adminpanel ap = new adminpanel();
ap.Show();
}
else
{
MessageBox.Show("Check Username or Password");
}
}
catch (Exception z)
{
MessageBox.Show("Connection error");
}

Related

C# Display data based on userID

Hi I'm creating a C# program where users can login and book bus seats for destinations, I have the program so users can insert/update/delete data but I want the data to just display the currently logged-in data, this is my code below.
This function is in the main dashboard class where it displays the seats table to the dataviewgrid
private void displayBookings()
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from seats";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
This is my database table and all I want to do once a user is logged in is display each seatID by the userID, the seatid is the primary key for this table and the userid is a foreign key linked to the userdata table.
EDIT:
private void displayBookings()
{
SqlConnection con = new SqlConnection(#"CONNECTIONSTRING");
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from seats WHERE userID = #userID";
//add the user id as a parameter
SqlParameter p_userID = new SqlParameter("#userID", SqlDbType.Int);
// the userID of the logged in user
p_userID.Value = cmd.Parameters.Add(p_userID);
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
Login method
private void loginButton_Click(object sender, EventArgs e)
{
StringBuilder errorMessages = new StringBuilder();
using (SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Brandon Brock\source\repos\SE2\Booking System\Database1.mdf;Integrated Security=True"))
{
con.Open();
string str1 = "select * from userdata where username='" + log_username.Text + "' and password_1='" + log_password.Text + "'";
SqlCommand cmd = new SqlCommand(str1, con);
try
{
SqlDataAdapter da = new SqlDataAdapter(str1, con);
da.SelectCommand.ExecuteNonQuery();
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count == 1)
{
switch (dt.Rows[0]["type"] as string)
{
case "admin":
{
MessageBox.Show("You are logged in!", "Admin Portal", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Hide();
new Admin().Show();
break;
}
case "user":
{
MessageBox.Show("You are logged in!", "Seat Reservation", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Hide();
new Dashboard().Show();
break;
}
default:
{
MessageBox.Show("Enter Correct Username and Password");
break;
}
}
log_username.Text = "";
log_password.Text = "";
}
else
{
MessageBox.Show("Username or Password is wrong or Account doesn't exist!", "Bus Seat Account Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (SqlException ex)
{
for (int i = 0; i < ex.Errors.Count; i++)
{
errorMessages.Append("Index #" + i + "\n" +
"Message: " + ex.Errors[i].Message + "\n" +
"LineNumber: " + ex.Errors[i].LineNumber + "\n" +
"Source: " + ex.Errors[i].Source + "\n" +
"Procedure: " + ex.Errors[i].Procedure + "\n");
}
Console.WriteLine(errorMessages.ToString());
}
}
}
Assuming you have access to the logged in user data:
con.Open(); // <-- can't see where this comes from but is almost certainly an anti-pattern. Don't re-use SqlConnection instances, make new ones and Dispose() when done.
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from seats WHERE userID = #userID";
//add the user id as a parameter
SqlParameter p_userID = new SqlParameter("#userID", SqlDbType.Int);
p_userID.Value = // the userID of the logged in user
cmd.Parameters.Add(p_userID);
//cmd.ExecuteNonQuery(); <-- this is pointless, delete it
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();

Multi user login using c# and ms access database, error is rows position?

Please help, on how to solve this one..
Here is my Login table's structure:
Username, Password, Position
Actually the code is running, and it shows the messagebox "Login Success". The problem is the form
frmHome home = new frmHome();
home.Show();
and
frmAdminHome ah = new frmAdminHome();
ah.Show();
did not show and throws an error on
if(dt.Rows[0][0].ToString()=="admin")
hmmp.. there's no row on position? seems its the errors says.
I need help on how to fix this one.. I need your guidance guys..
This code is on button click event, I am using C# and MS Access database:
try
{
string user, pass;
user = Convert.ToString(txtUsername.Text);
pass = Convert.ToString(txtPassword.Text);
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM Login WHERE Username = '" +user+ "' AND Password = '" + pass + "' ";
OleDbDataAdapter da = new OleDbDataAdapter();
OleDbDataReader reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
int count = 0;
while (reader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Login Success!");
this.Hide();
if (dt.Rows[0][0].ToString()=="admin")
{
frmHome home = new frmHome();
home.Show();
Visible = false;
}
else if (dt.Rows[0][0].ToString() == "staff")
{
frmAdminHome ah = new frmAdminHome();
ah.Show();
Visible = false;
}
}
else if (count > 1)
{
MessageBox.Show("Duplicate username and password!");
}
else
{
MessageBox.Show("Username and Password is not correct!");
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("ERROR" + ex);
}
First thing is you should not have duplicate rows having same username and password.
this should be prevented when user is created in the system. You should not allow duplicate usernames. If you handle that you won't need to check for duplicates at the time of login.
For now you can use following approach to solve your current issue.
You are getting data returned from the query into the DataReader and you read it using reader.Read() but you never populate the datatable using OleDbDataAdapter da
try
{
string user, pass;
user = txtUsername.Text; // You don't need Convert.ToString as TextBox.Text is already string.
pass = txtPassword.Text;
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
var query = "SELECT * FROM Login WHERE Username = '" +user+ "' AND Password = '" + pass + "' ";
OleDbDataAdapter da = new OleDbDataAdapter(query, con);
DataSet ds = new DataSet();
da.Fill(ds); //Populate data set via adapter.
DataTable dt = ds.Tables[0]; //Get the first table from the dataset
int count = dt.Rows.Count;
if (count == 1)
{
MessageBox.Show("Login Success!");
this.Hide();
if (dt.Rows[0][0].ToString()=="admin")
{
frmHome home = new frmHome();
home.Show();
Visible = false;
}
else if (dt.Rows[0][0].ToString() == "staff")
{
frmAdminHome ah = new frmAdminHome();
ah.Show();
Visible = false;
}
}
else if (count > 1)
{
MessageBox.Show("Duplicate username and password!");
}
else
{
MessageBox.Show("Username and Password is not correct!");
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("ERROR" + ex);
}
This should help you resolve your issue.

Why is nothing showing up in my DataGridView?

I'm trying to initialize a DataGridView object. All I did was add the object to my screen without changing any properties. I have code that is run when the user selects the panel it is on. The code looks like this...
DataTable tbl = new DataTable();
string query = "SELECT viewfolder, status FROM Folders WHERE username = '" + Globals.usrName + "' ORDER BY viewfolder";
SqlConnection connect = new SqlConnection(#"Data Source=(LocalDB)\v11.0;" +
#"AttachDbFilename=C:\Development\C-Sharp\LockItUp\Lockitup.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand(query, connect);
connect.Open();
try
{
SqlDataAdapter dAdapt = new SqlDataAdapter(cmd);
dAdapt.Fill(tbl);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
connect.Close();
dataGridView1.DataSource = tbl;
So is there any other code I have to add or properties I have to set to see the data appear on the grid? Thanks for the help.
Can you try using this code:
void FillData()
{
using (SqlConnection c = new SqlConnection(
#"Data Source=(LocalDB)\v11.0;" +
#"AttachDbFilename=C:\Development\C-Sharp\LockItUp\Lockitup.mdf;Integrated Security=True"))
{
c.Open();
string query = "SELECT viewfolder, status FROM Folders WHERE username = '" + Globals.usrName + "' ORDER BY viewfolder";
using (SqlDataAdapter a = new SqlDataAdapter(
query , c))
{
DataTable tbl = new DataTable();
a.Fill(tbl);
dataGridView1.DataSource = tbl;
}
}
}

Login page logical error

I am developing website using ASP.NET 4.0 , C# and SQL Server 2008. In my Login page, same user should login many times at the time of registration. After his 'Step-I' registration, the user will wait for Admin Approval. After the 'Admin Approval only' the user can redirect to 'Step-II' registration page. So I write code like below. But based upon my code, without the admin Approval, the page redirect to 'step II' registration when user login second time. How to prevent it ? Need help.
protected void BtnHomeUserSubmit_Click(object sender, EventArgs e)
{
SqlConnection SqlCon = new SqlConnection(GetConnectionString());
try
{
var da1 = new SqlDataAdapter
("select * from User_Info2 where Vendor_ID ='" + txtHomeUsername.Text.Trim() + "'
AND User_Password='" + txtHomePassword.Text.Trim() + "'", SqlCon);
var dt1 = new DataTable();
da1.Fill(dt1);
if (dt1.Rows.Count == 0)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert",
"alert('Enter valid Vendor ID and Password');", true);
}
else
{
var da2 = new SqlDataAdapter
("select * from Company_Info where Vendor_ID='"+ txtHomeUsername.Text+"'
AND Approval_Status='NO' OR Approval_Status='PEN'", SqlCon);
var dt2 = new DataTable();
da2.Fill(dt2);
if (dt2.Rows.Count > 0)
{
string url = "../ApprovalStatus2.aspx?Parameter=" + Server.UrlEncode(txtHomeUsername.Text);
ClientScript.RegisterStartupScript(this.GetType(),
"callfunction","alert('Vendor ID is waiting for Approval');
window.location.href = '" + url + "';", true);
}
var da3 = new SqlDataAdapter
("select Vendor_ID from RegPage1 where Vendor_ID='" + txtHomeUsername.Text.Trim() + "'",SqlCon);
var dt3 = new DataTable();
da3.Fill(dt3);
if (dt3.Rows.Count > 0)
{
string url = "../UserLogin.aspx";
ClientScript.RegisterStartupScript(this.GetType(),"callfunction","alert
('Vendor ID already completed the registration');window.location.href ='" + url + "';", true);
}
else
{
Response.Redirect("~/RegPage1.aspx?Parameter=" + Server.UrlEncode(txtHomeUsername.Text));
}
}
}
finally
{
SqlCon.Close();
}
Code change: Please check and let me know
protected void BtnHomeUserSubmit_Click(object sender, EventArgs e)
{
SqlConnection SqlCon = new SqlConnection(GetConnectionString());
try
{
var da1 = new SqlDataAdapter
("select * from User_Info2 where Vendor_ID ='" + txtHomeUsername.Text.Trim() + "'
AND User_Password='" + txtHomePassword.Text.Trim() + "'", SqlCon);
var dt1 = new DataTable();
da1.Fill(dt1);
if (dt1.Rows.Count == 0)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert",
"alert('Enter valid Vendor ID and Password');", true);
}
else
{
var da2 = new SqlDataAdapter
("select * from Company_Info where Vendor_ID='"+ txtHomeUsername.Text+"'
AND (Approval_Status='NO' OR Approval_Status='PEN')", SqlCon);
var dt2 = new DataTable();
da2.Fill(dt2);
if (dt2.Rows.Count > 0)
{
string url = "../ApprovalStatus2.aspx?Parameter=" +
Server.UrlEncode(txtHomeUsername.Text);
ClientScript.RegisterStartupScript(this.GetType(),
"callfunction","alert('Vendor ID is waiting for Approval');
window.location.href = '" + url + "';", true);
}
else
{
var da3 = new SqlDataAdapter
("select Vendor_ID from RegPage1 where Vendor_ID='" +
txtHomeUsername.Text.Trim() + "'",SqlCon);
var dt3 = new DataTable();
da3.Fill(dt3);
if (dt3.Rows.Count > 0)
{
string url = "../UserLogin.aspx";
ClientScript.RegisterStartupScript(this.GetType(),"callfunction",
"alert('Vendor ID already completed the
registration');window.location.href ='" + url + "';", true);
}
else
{
Response.Redirect("~/RegPage1.aspx?Parameter=" +
Server.UrlEncode(txtHomeUsername.Text));
}
}
}
}
finally
{
SqlCon.Close();
}
Change your coding like this:
var da2 = new SqlDataAdapter
("select * from Company_Info where Vendor_ID='"+ txtHomeUsername.Text+"'
AND (Approval_Status='NO' OR Approval_Status='PEN')", SqlCon);
Please let me know if it helps.

No value given for one or more required parameters.()

I have a problem, when i m login the error is occured that No value given for one or more required parameters.
protected void imgbtn_login_Click(object sender, ImageClickEventArgs e)
{
int UserId = 0;
string str = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=pathto.mdb;Persist Security Info=False;");
OleDbConnection conn = new OleDbConnection(str);
conn.Open();
string query = "select * from Users where LoginName='" + txt_logname.Text + "' and Password='" + txt_pass.Text + "';";
OleDbDataAdapter da=new OleDbDataAdapter(query,conn);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = new DataTable();
dt = ds.Tables[0];
try
{
UserId = Int32.Parse(dt.Rows[0]["UserId"].ToString());
//btn_LogIn.Text = "Login Succeded";
Response.Redirect("Register.aspx");
}
catch (Exception ex)
{
}
txt_logname.Text = " ";
txt_pass.Text = "";
}
Password is a reserved word. Put it in square brackets [Password]
See Syntax error in INSERT INTO statement

Categories