I don't get the while loop executed - c#

I can't make out what is the mistake. I wanted to retrieve a record from the database table and give them out. There are 9 fields in my table. The data of the second field is the search word. There can be more than one record for the same data. If there are many, then it must show each record at a time. How is it possible to code it?
I use C#.Net for logic and Ms Access for the back end(Database)
This is my code:
string[] arr = new string[9];
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="C:\PassWordSaver\Passwords.mdb;Persist Security Info=True;");
con.Open();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM pwd Where Title = '"+textBox2+"'", con);
OleDbDataReader reader = cmd.ExecuteReader();
reader.Read();
//while (reader.Read())
//{
for (int i = 0; i < 9; i++)
{
arr[i] = reader.GetValue(i).ToString();
MessageBox.Show("The New data is " + arr[i] + ".", "Created", MessageBoxButtons.OK);
}
//}
reader.Close();
MessageBox.Show("Data Added Successfully. " + arr[2] + " is the user name.", "Created", MessageBoxButtons.OK);

OleDbCommand cmd = new OleDbCommand("SELECT * FROM pwd Where Title = '"+textBox2+"'", con);
Should read:
OleDbCommand cmd = new OleDbCommand("SELECT * FROM pwd Where Title = '"+textBox2.Text+"'", con);
The reason you aren't entering your while loop is that the condition isn't being met to begin with. There is nothing for myReader to read. However, I don't understand why you don't get an error when you run that telling you that you can't convert a textbox control to a string.

First of all you're getting into the loop because your query doesn't return any results, and second of all you might want to try and put some parameters on this query like so:
OleDbCommand cmd = new OleDbCommand("SELECT * FROM pwd Where Title = ?", con);
cmd.Parameters.Add(textBox2.Text); // I assume you mean textBox2.Text

May be it will be a silly answer but I think you are trying to send query by taking the value from textbox.Text property. But on the code you are trying to get directly Textbox
OleDbCommand cmd = new OleDbCommand("SELECT * FROM pwd Where Title = '"+textBox2+"'", con);
I think you can update as follows
OleDbCommand cmd = new OleDbCommand("SELECT * FROM pwd Where Title = '"+textBox2.Text+"'", con);

Related

Why is the 2nd Command inside a Connection does not work?

I'm trying to do a test in two tables based on what the user entered in the login TextBox, So I test the LoginName if it is in Table "Redacteur"; else I make a new Command that will look inside another table "Membres".
Problem is: the command works when I enter a loginName that is in the table "Redacteur", but Once I enter a loginName that belongs to the Membres's table It doesn't redirect me to the page I'm requesting inside the code. I think it doesn't even enter the Else section.
using(SqlConnection connect = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("select * from Redacteurs where RedCode= #lg", connect);
cmd.Parameters.AddWithValue("#lg", TextLogIn.Text);
connect.Open();
//cmd.ExecuteNonQuery();
SqlDataReader rd = cmd.ExecuteReader();
if (rd.HasRows)
{
rd.Read();
Session["code"] = rd["RedCode"].ToString();
Session["loginname"] = TextLogIn.Text;
Session["pass"] = TextPass.Value;
Response.Redirect("RedacteurPage.aspx?Redact="
+ Session["loginname"].ToString());
rd.Close();
}
else
{
cmd = new SqlCommand("select * from Membres where LoginMembre = #lm", connect);
cmd.Parameters.AddWithValue("#lm", TextLogIn.Text);
//cmd.ExecuteNonQuery();
SqlDataReader rd2 = cmd.ExecuteReader();
if (rd2.HasRows)
{
rd2.Read();
Session["code"] = rd2["MembreCode"].ToString();
Session["loginname"] = TextLogIn.Text;
Session["pass"] = TextPass.Value;
Response.Redirect("ProductCatalogue.aspx?user=" + rd2["FullName"]);
rd2.Close();
}
}
}
You need to close/dispose the first command before you can execute one on the same connection.
The quick-and-dirty (i.e. works but not recommended) solution would be to have rd.Close() in the first line of your else block.

C# checking if order number already exists

I've been looking into How to check user id already exists to see how to do this.
I am trying to get this working in my code, however it's not working. I don't get errors or something, but it just write data in database even if order number already exists.
The function:
private void createorderButton_Click(object sender, EventArgs e)
{
SqlConnection myConnection = dbHelper.initiallizeDB();
String query = "INSERT INTO testtabel (knaam, korder) VALUES ('" + knaamTextBox.Text + "','" + kordernrTextBox.Text + "')";
SqlCommand sqlCommand = new SqlCommand(query, myConnection);
SqlCommand cmd = new SqlCommand("select * from testtabel where korder = #korder", myConnection);
SqlParameter param = new SqlParameter();
param.ParameterName = "#korder";
param.Value = kordernrTextBox.Text;
cmd.Parameters.Add(param);
//sqlCommand.Connection.Open();
SqlDataReader reader = sqlCommand.ExecuteReader();
if (reader.HasRows)
{
MessageBox.Show("Order already exist");
}
else
{
reader.Close();
}
// opens execute non query
int rows_inserted = sqlCommand.ExecuteNonQuery();
if (rows_inserted > 0)
{
label2.Text = "Order has been created";
}
else
{
Console.Write("Oops! Something wrong!");
}
}
Sorry for this kinda well known and duplicated question, but for some reason I can't get it working.
You called the wrong command, change
SqlDataReader reader = sqlCommand.ExecuteReader();
to
SqlDataReader reader = cmd.ExecuteReader();
The problem is here:
SqlDataReader reader = sqlCommand.ExecuteReader();
You should execute the other command first
SqlCommand cmd = new SqlCommand("select * from testtabel where korder = #korder", myConnection);
The latter command, when will be executed will tell you if there is any record in the testtabel table. If there is, then you should show the message:
Order already exist
Otherwise, you will execute your first command, that will insert the rows.
By the way, please try to avoid string concatenation, when you write sql queries. It is one of the most well known security holes. You code is open to SQL injections. You could use parameterized queries:
String query = "INSERT INTO testtabel (knaam, korder) VALUES (#knaam, #korder)";
SqlCommand sqlCommand = new SqlCommand(query, myConnection);
sqlCommand.Parameters.Add(new SqlParamete("#knaam",knaamTextBox.Text));
sqlCommand.Parameters.Add(new SqlParamete("#korder",kordernrTextBox.Text));
While your code is full of problems (magic pushbutton, SQL injections, absence of usings), there is main one. The approach you want to implement will fail on concurrent inserts, and must not be used.
Imagine, that two users run this code against the same database, using the same korder value:
1st executes SELECT - record with the given value doesn't exist;
2nd executes SELECT - record with the given value doesn't exist;
1st executes INSERT - record with the given value does exist;
2nd executes INSERT - ooops... we have a duplicate;
To avoid duplicates you must use unique indexes in database. Do not rely on your code.
You check HasRows for INSERT INTO testtabel bla...bla..bla.. not for `elect * from testtabel where korder'
Maybe you can use this (it comes from my head and not compiled, please adjust it with your own case)
private void createorderButton_Click(object sender, EventArgs e)
{
SqlConnection myConnection = dbHelper.initiallizeDB();
String query = "INSERT INTO testtabel (knaam, korder) VALUES ('" + knaamTextBox.Text + "','" + kordernrTextBox.Text + "')";
SqlCommand sqlCommand = new SqlCommand(query, myConnection);
SqlCommand cmd = new SqlCommand("select * from testtabel where korder = #korder", myConnection);
SqlParameter param = new SqlParameter();
param.ParameterName = "#korder";
param.Value = kordernrTextBox.Text;
//sqlCommand.Connection.Open();
SqlDataReader cmdReader = sqlCommand.ExecuteReader();
if (cmdReader.HasRows)
{
MessageBox.Show("Order already exist");
}
else
{
cmdReader.Close();
}
SqlDataReader reader = sqlCommand.ExecuteReader();
// opens execute non query
int rows_inserted = sqlCommand.ExecuteNonQuery();
if (rows_inserted > 0)
{
label2.Text = "Order has been created";
}
else
{
Console.Write("Oops! Something wrong!");
}
}

Select * From table Where column Like statement c#

I failed to get the correct result with this code in Form2:
conn.Open();
OleDbCommand cmd = new OleDbCommand("Select * From udbTable Where Username Like '" + f1.textBox1.Text + "%'", conn);
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
label5.Text = reader["Username"].ToString();
}
conn.Close();
I have 3 samples data in the table, but i'm always getting the same result which is the first entry of the database. Whenever i input the last entry or second entry in the textbox1.Text, i still getting the first entry.
textbox1.Text is from Form1, and i set it's property Modification to Public.
label5.text is the output.
try this fix
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection=conn;
command.CommandText = "Select * From udbTable Where Username Like ?";
cmd.Parameters.Add("#Username",OleDbType.VarChar);
cmd.Parameters["#Username"].Value=f1.textBox1.Text;
OleDbDataReader reader = cmd.ExecuteReader();

How to get/display the user-information after logging in. ASP.net C#

I am implementing an online voting system for my school-project.
After the voter's log-in, i want to display their name, and ID in the label control at the content body. I try to use SESSION to store the voter's username in the log-in page but I'm not sure of my syntax because nothings happen.
I want to know the other way of retrieving a data from database! Please teach me.
public void GetInformation()
{
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = connection;
cmd.CommandText = "SELECT * FROM tblUsers WHERE voter_name = '" + Session["VotersID"] + "'";
OleDbDataReader reader = cmd.ExecuteReader();
if(reader.Read())
{
lblVoterName.Text = reader["usr_FirstN"].ToString() + " " + reader["usr_LastN"].ToString();
}
}
Please Help Me. Thanks! -
#Honey Maglangit , what you use is PARAMETER not SESSION.
Response.Redirect("VoterPage.aspx?VotersID="+VoterUsername.Text);
So, you should get your VotersID by this way:
public void GetInformation()
{
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = connection;
cmd.CommandText = "SELECT * FROM tblUsers WHERE voter_name = '" + Request.QueryString["VotersID"].ToString() + "'";
OleDbDataReader reader = cmd.ExecuteReader();
if(reader.Read())
{
lblVoterName.Text = reader["usr_FirstN"].ToString() + " " + reader["usr_LastN"].ToString();
}
}
Try it again.
You can use LogonUserIdentity as follow
if (Request.LogonUserIdentity.IsAuthenticated)
lblName.Text = Request.LogonUserIdentity.Name;
just add this namespace:
using Microsoft.AspNet.Identity;
then you can get LoggedInUserId by:
User.Identity.GetUserId();
Or
HttpContext.Current.User.Identity.GetUserId();
So you don't need to use session to keep UserId.
Also you can create Custom Identity and instead of save Username in Name property, storing custom string Store User Data in ASP.NET Identity
get session data and send to one page(register.aspx) to another page(user_home.aspx)
Session["remail2"] = txtemailsignin.Text;
Server.Transfer("user_home.aspx", true);
display the user-information after logging
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["socailweb"].ConnectionString);
string sql = "select * from tblUsers where remail='" + Session["remail2"] + "'";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader sqldr = cmd.ExecuteReader();
if (sqldr.Read() == true)
{
lblVotersID.Text = sqldr.GetValue(2).ToString();
lblVoterName.Text = sqldr.GetValue(3).ToString();
}
sqldr.Close();
con.Close();

syntax error in from clause C# and Access

I keep getting this run time error, syntax error in from clause. I tried already using my sql query in access and it seems ok.
Here's my code and I am using C# windows form with text box and button
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Misry27\Documents\Visual Studio 2010\Projects\Inventory\Inventory\bin\Debug\Inventory.mdb");
OleDbCommand cmd = new OleDbCommand("select * from Employee where username = '" + this.tbUsername.Text + "' and password = '" + this.tbPassword.Text + "';", conn);
OleDbDataReader dr;
conn.Open();
dr = cmd.ExecuteReader();
int count = 0;
while (dr.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Username or Password is correct");
}
else
{
MessageBox.Show("Username or Password Incorrect");
}
conn.Close();
As explained in the comments above, PASSWORD is a reserved keyword and need to be enclosed in square brackets when used in query executed from net.
The usual advice follows. Use parameterized query to avoid parsing problem and sql injections, use the using statement around your disposable objects.
using(OleDbConnection conn = new OleDbConnection(a correct connection string here))
using(OleDbCommand cmd = new OleDbCommand(#"select * from Employee
where username = ? AND [Password] = ?", conn);
{
conn.Open();
cmd.Parameters.AddWithValue("#p1", this.tbUsername.Text);
cmd.Parameters.AddWithValue("#p2", this.tbPassword.Text);
using(OleDbDataReader dr = cmd.ExecuteReader())
{
.....
}
}

Categories

Resources