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();
Related
I have two tables in the database one is UserAuth and the other is CarAdd, but I need to show UserName from the UserAuth table in my CarAdd dataGridView1 section.
This method shows all data from my CarAdd table:
void Bindata()
{
SqlCommand cmd = new SqlCommand("select * from CarAdd", con);
SqlDataAdapter sd = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sd.Fill(dt);
dataGridView1.ItemsSource = dt.DefaultView;
}
But, now I need to show the username from the UserAuth table in the dataGridView1 section.
I have tried this code:
void BindataUserName()
{
SqlCommand cmd = new SqlCommand("select * from UsreAuth where UserName='UserName'", con);
SqlDataAdapter sd = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sd.Fill(dt);
// dataGridView1.ItemsSource = dt.DefaultView;
}
Here is my save click button, actually I need to save and show username on dataGridView1 after click this button:
private void save_Click(object sender, RoutedEventArgs e)
{
if (carid.Text != "" && cartype.Text != "" && model.Text != "" && intime.Text!="" && outtime.Text!="" && slotgroup.Text!="")
{
try
{
con.Open();
string newcon = "insert into CarAdd (carid, cartype, carmodel, duration, payment, slot_book, insertdate) values ('" + carid.Text + "','" + cartype.Text + "','" + model.Text + "', '" +txtduration.Text+ "','" +txtpayment.Text+ "','"+ slotgroup.Text +"' ,getdate())";
SqlCommand cmd = new SqlCommand(newcon, con);
cmd.ExecuteNonQuery();
MessageBox.Show("Successfully inserted");
Bindata();
// TimeShow();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
else
{
MessageBox.Show("Invalid credentials");
}
}
Note: I have created a WPF Windows application for this project
Thank you!
Since UserName is an attribute in the UserAuth table, the SQL query must be modified accordingly to fetch it.
SELECT UserName
FROM UserAuth
So for the Bindatausername() method, the SqlCommand should be changed to the following:
void BindataUserName()
{
SqlCommand cmd = new SqlCommand("select UserName from UserAuth where UserName='UserName'", con);
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.
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");
}
This is my code and error message when you running say:
An unhandled exception of type System.Data.SqlClient.SqlException
occurred in System.Data.dll
on this da.fill(dt);
SqlConnection con = new SqlConnection("Data Source=ANTONIANGGA-PC\\SQLEXPRESS;Initial Catalog=FullandStarving;Integrated Security=True");
SqlCommand cmd;
SqlDataAdapter da;
DataTable dt = new DataTable();
public FormProduksi()
{
InitializeComponent();
showgridview();
}
private void showgridview()
{
con.Open();
dt.Clear();
cmd = new SqlCommand("SELECT * FROM Produksi", con);
//cmd.CommandType = CommandType.StoredProcedure; done :D
da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
private void button2_Click(object sender, EventArgs e)
{
//Datetimepicker to Database
string dProduksi = DateTime.Parse(dtmProduksi.Text).ToString("yyyy-MM-dd");
try{
con.Open();
cmd = new SqlCommand("insert into Produksi (IDProduksi,IDPhoto,TanggalProduksi,NamaKaryawan,KeteranganPhoto) Values('" + txtIdpro.Text + "','" + txtIdPhoto.Text + "','" + dProduksi + "','" + txtNamaKaryawan.Text + "','" + rxtKtrphoto.Text + "')", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Update telah di jalankan");
showgridview();
clear();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
that update successfully but cant refresh, so i do quit that form and open can see it
You are closing the connection
con.Close();
and then using
da.Fill(dt);
Just swap this lines:
showgridview();
con.Close();
For example with DbDataAdapter.Fill:
Notes:
1
Yoy should use parametrized queries so you avoid SQL Injection attacks:
var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = #id", con);
cmd.Parameters.AddWithValue("#id", id.Text);
2
Wrap SqlConnection and SqlCommand into using so any resources used by those would disposed:
string position;
using (SqlConnection con = new SqlConnection("server=free-pc\\FATMAH; Integrated Security=True; database=Workflow; "))
{
con.Open();
using (var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = #id", con))
{
cmd.Parameters.AddWithValue("#id", id.Text);
var name = cmd.ExecuteScalar();
if (name != null)
{
position = name.ToString();
Response.Write("User Registration successful");
}
else
{
Console.WriteLine("No Employee found.");
}
}
}
Credit
Just change the showgridview() function as below where connection is opened & closed properly.
Also check your sql query ,provide space and maintain syntax of query :
SELECT * FROM Produksi
Error screenshot clearly depicts that stored procedure with such name don't exist
comment out those lines as code below :
void showgridview()
{
con.Open();
dt.Clear();
cmd = new SqlCommand("SELECT * FROM Produksi", con);
//cmd.CommandType = CommandType.StoredProcedure;
da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
Then you wont be having connection issues and errors related .
Button Click code change the closing connection as below:
private void button2_Click(object sender, EventArgs e)
{
//Datetimepicker to Database
string dProduksi = DateTime.Parse(dtmProduksi.Text).ToString("yyyy-MM-dd");
try
{
con.Open();
cmd = new SqlCommand("insert into Produksi (IDProduksi,IDPhoto,TanggalProduksi,NamaKaryawan,KeteranganPhoto) Values('" + txtIdpro.Text + "','" + txtIdPhoto.Text + "','" + dProduksi + "','" + txtNamaKaryawan.Text + "','" + rxtKtrphoto.Text + "')", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Update telah di jalankan");
con.Close();
showgridview();
clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Also, for further reading:
parameterized queries vs. SQL injection
Why do we always prefer using parameters in SQL statements?
try
{
UserMaster ObjUserMst = new UserMaster();
ObjUserMst.GetData("UPDATE MemberDetails SET Active = 0 WHERE Member_No = '" + txtmemberno.Text + "'");
MessageBox.Show("Installment Close Successfully.", "Close Installment", MessageBoxButtons.OK, MessageBoxIcon.Information);
btndebit.Visible = true;
btndebit.Visible = false;
}
catch (Exception ex)
{
XtraMessageBox.Show(ex.Message.ToString(), "btncloseinstallment_Click", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
its get data code
public DataTable GetData(string Query)
{
string cn = GlobalClass.ConnectionStringGet();
Con = new SqlConnection(cn);
cmd = new SqlCommand();
cmd.Connection = Con;
if (cmd.Connection.State == ConnectionState.Closed)
{
cmd.Connection.Open();
}
SqlTransaction ObjTrans = cmd.Connection.BeginTransaction();
cmd.Transaction = ObjTrans;
cmd.CommandType = CommandType.Text;
cmd.CommandText = Query;
cmd.CommandTimeout = 500;
SqlDataReader dreader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dreader);
Con.Close();
Con.Dispose();
return dt;
}
i have winforms.
i have memberdetails Table - in this Active Field & its datatype is BIT. its
default value is 1. but i need to update it to 0.
1 = ture
0 = false
when i tried above code Active Field data didnt update
but i got message "Installment Close Successfully."
http://i.stack.imgur.com/mkuhW.png
http://i.stack.imgur.com/ToXFV.png
I upload my images on above link
help me guys.. sorry if i didnt explain very well bcz i m new here
ok i got it.
string constring = GlobalClass.ConnectionStringGet();
string sqlUpdate = "UPDATE MemberDetails SET Active = '0' WHERE Member_No = '" + txtmemberno.Text + "'";
SqlConnection conDatabase = new SqlConnection(constring);
SqlCommand cmdd = new SqlCommand(sqlUpdate, conDatabase);
conDatabase.Open();
cmdd.ExecuteNonQuery();
conDatabase.Close();
MessageBox.Show("Installment Close Successfully.");
its update Active Field 1 to 0 successfully.