So i've created a application that is linked to a MS Acces database. I have a login system and when the login is succesful, their Personal data is displayed in some textboxes. One of these textboxes shows their PersonID (the ID for acces database).
User can make a appointment. This will be written in the database under UserID - Appointment date - Treatment. I want to retrieve this info and shows it into my listbox. But don't know why, because it needs to only retrieve the data that is linked to the logged in UserID ofcourse.
I have something like this but i'm stuck right now.
connection.Open();
OleDbCommand command = new OleDbCommand();
string afspraken = "select * from Appointments where PersonID = '" + textBox4.Text + "'";
OleDbDataReader reader = command.ExecuteReader();
listBox2.DataSource = reader;
connection.Close();
DataTable dt = new DataTable();
OleDbCommand command = new OleDbCommand();
string afspraken = "select * from Appointments where PersonID = '" + textBox4.Text + "'";
OleDbDataReader reader = command.ExecuteReader();
dt.Load(reader);
foreach (DataRow Dr in dt.Rows)
{
listBox1.Items.Add(Dr["COLUMNNAME"].ToString());
}
con.Close();
Try This ...
Related
I'm trying to update my MS Access database with a a foreach loop which iterates over all rows of my DataTable object which I see in my DataGrid (WPF); it should update the table in the database.
After I made some changes in a row of a column, I want to save them. But my SQL command only reacts one time (last loop). The MessageBox shows the correct row I want to update in every loop. But when I open the database again the whole column is empty.
Hope someone can help me :) I'm an absolute beginner to programming btw
OleDbCommand Command2 = new OleDbCommand();
Command2.Connection = Connection;
Connection.Open();
foreach (DataRow DR1 in DT1.Rows)
{
string S1 = Convert.ToString(DR1["Column1"]);
MessageBox.Show("Current Row: " + S1 +" will be updated");
Command2.CommandText = "UPDATE Table1 SET Column1= '" + S1 + "' WHERE ID = 0 ";
Command2.ExecuteNonQuery();
}
Connection.Close();
This has worked for me :)
foreach (DataRow DR1 in DT1.Rows)
{
DA1.UpdateCommand = new OleDbCommand("UPDATE Table1 SET Column1 = #Column1 WHERE ID= #ID", Connection);
DA1.UpdateCommand.Parameters.Add("#Column1", OleDbType.VarChar).Value = Convert.ToString(DR1["Column1"]);
DA1.UpdateCommand.Parameters.Add("#ID", OleDbType.VarChar).Value = Convert.ToString(DR1["ID"]);
DA1.UpdateCommand.ExecuteNonQuery();
}
I'm trying to retrieve multiple cells in different rows where the correct owner exists, but I'm only being able to retrieve the first match and it stops there, I've tried using it with a for, but I don't think .ExecuteScalar() is the way to do this. Maybe I'm just stupid and doing it completely wrong.
Code:
checkPlayerName = API.getPlayerName(player);
string checkOwnedCars = "SELECT COUNT(*) FROM [carOwners] WHERE Owner='" + checkPlayerName + "'";
con.Open();
SqlCommand checkCarsCount = new SqlCommand(checkOwnedCars, con);
int carsCountToVar = Convert.ToInt32(checkCarsCount.ExecuteScalar());
con.Close();
for (int i = 0; i < carsCountToVar; i++)
{
string displayCars = "SELECT LP FROM [carOwners] WHERE Owner='" + checkPlayerName + "'";
con.Open();
SqlCommand displayCarsCMD = new SqlCommand(displayCars, con);
string displayCarsToVar = displayCarsCMD.ExecuteReader().ToString();
API.sendChatMessageToPlayer(player, "Owned Vehicle: " + displayCarsToVar.ToString());
con.Close();
}
Table
For example, LP on 2nd and 3rd row are the ones that I want to store since both belong to the same owner, yet only first cell data (1337) is displaying.
You are not iterating the results you are getting from query.
Plus always use Parameterized queries to prevent SQL Injection Attacks
SqlCommand command = new SqlCommand("SELECT LP FROM [carOwners] WHERE Owner=#checkPlayerName", con);
command.Parameters.AddWithValue("#checkPlayerName",checkPlayerName);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}",reader["id"]));
//API.sendChatMessageToPlayer(player, "Owned Vehicle: " + reader["id"].ToString());
}
}
conn.Close();
Im trying to display user data from database into textbox, so that user can edit/update that data later.
Im getting error of no value has been set for at least one of the required parameters.
I did not write the SELECT * FROM, because i'm not displaying data like AdminRights.
Can you please help me fix the error?
This is my code
private void refresh_Click(object sender, RoutedEventArgs e)
{
if (!isPostBack)
{
DataTable dt = new DataTable();
con.Open();
OleDbDataReader dr = null;
OleDbCommand cmd = new OleDbCommand("SELECT [Name], [LastName], [UserName], [Password], [Address], [Email] FROM User WHERE [ID] = ?", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
name.Text = (dr["Name"].ToString());
lName.Text = (dr["LastName"].ToString());
uName.Text = (dr["UserName"].ToString());
pass.Text = (dr["Password"].ToString());
address.Text = (dr["Address"].ToString());
email.Text = (dr["Email"].ToString());
id.Text = (dr["ID"].ToString());
}
con.Close();
}
}
.....FROM User WHERE [ID] = ?", con);
The ? placeholder requires a parameter defined in the command parameters collection.
So, before calling ExecuteReader you need to add the parameter for the ID field
cmd.Parameters.AddWithValue("#p1", ????value for the ID field);
dr = cmd.ExecuteReader();
If you want to retrieve a single record from your table you need to know the value for the field that uniquely identifies the records in your table.
To get that value it is necessary to understand how do you reach this code. If you select a row from a list, grid or combo, probably you have loaded that control with your user names and their ID.
String id = idTextBox.Text;
OleDbCommand command = new OleDbCommand("Select *from User Where [ID]= "+ id +" ");
command.Connection = conn;
OleDbDataReader dr = null;
conn.Open();
dr = command.ExecuteReader();
while (dr.Read())
{
name.Text = (dr["Name"].ToString());
lName.Text = (dr["LastName"].ToString());
uName.Text = (dr["UserName"].ToString());
pass.Text = (dr["Password"].ToString());
address.Text = (dr["Address"].ToString());
email.Text = (dr["Email"].ToString());
id.Text = (dr["ID"].ToString());
}
conn.Close();
this will work fine change lines and execute
I want to fetch all rows that related to the query below, my problem that only one row retrived not all rows , iam using asp.net with c# and ado.net and my code logic is
if (!IsPostBack)
{
string username = Session["username"].ToString();
con.Open();
string strqryScript = "select * from dbo.teachers where user_id = '" + username + "'";
SqlCommand cmd = new SqlCommand(strqryScript, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataReader rdr = cmd.ExecuteReader();
rdr.Read();
string name = rdr["teach_id"].ToString();
rdr.Close();
string query = "select * from dbo.teacher_classes where teach_id = '" + name + "' ORDER BY class_id";
SqlCommand cmd2 = new SqlCommand(query, con);
SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
SqlDataReader rdr2 = cmd2.ExecuteReader();
while (rdr2.Read())
{
classname.Text = rdr2["class_id"].ToString();
}
con.Close();
}
extra note that i can use gridview to bind data but i want to fill my table with custom information from many tables , so i want to use an html table and fill it with my custom data. any help please! and thanks ..
While looping on the second reader, you write the value extracted from the reader on the Text property of the classname label. This will overwrite the previous text and leave you with the name of the last teacher retrieved. You need to add to the previous text or use a List.
classname.Text += rdr2["class_id"].ToString();
Said that, let me point you to a big problem in your code. String concatenation is really bad when you build sql commands. It gives you back syntax errors (if your input text contains single quotes) or Sql Injection as explained here
You should use parameterized queries like this (just for your first command)
string strqryScript = "select * from dbo.teachers where user_id = #id";
SqlCommand cmd = new SqlCommand(strqryScript, con);
cmd.Parameters.AddWitValue("#id", username);
....
This is the issue you need to fix:
classname.Text = rdr2["class_id"].ToString(); <== always setting the same text!!
You need to make sure, you fill a list, a dataset or whatever, when reading the data!
does anyone know how do I get the StudentID from Students table, store it in datareader or dataset, and then use it to update another table, which is Users Table, because I want the username and password of users would be their StudentID as a default. BTW, this is C# ASP.NET.
Here is my code.
SqlConnection conUpdate = new SqlConnection(GetConnectionString());
conUpdate.Open();
SqlCommand com2 = new SqlCommand();
com2.Connection = conUpdate;
com2.CommandText = "SELECT Students.StudentID, Users.UserID FROM Students, Users " +
"WHERE Students.UserID = Users.UserID";
int UserId = ((int)com2.ExecuteScalar());
com2.CommandText = "SELECT MAX(StudentID) FROM Students";
int StudentId = ((int)com2.ExecuteScalar());
com2.CommandType = CommandType.Text;
com2.CommandText = "UPDATE Users SET UserName=#UserName, Password=#Password WHERE UserID=#UserID";
com2.Parameters.Add("#UserName", SqlDbType.NVarChar);
com2.Parameters.Add("#Password", SqlDbType.NVarChar);
com2.Parameters[0].Value = reader;
com2.Parameters[1].Value = reader;
com2.ExecuteNonQuery();
conUpdate.Close();
conUpdate.Dispose();
Since you already getting UserId in your select query, you should get the value using DataReader. like this:
// Execute the query
SqlDataReader rdr = cmd.ExecuteReader();
int UserId;
while(rdr.Read())
{
UserId = Convert.ToInt32(rdr["UserID"].ToString());
}
Your command com2.CommandText = "SELECT MAX(StudentID) FROM Students"; will return the Max student ID, and that is probably not needed. Your earlier command com2.CommandText = "SELECT Students.StudentID, Users.UserID .... is what you need to get the student UserID.
You can use Data reader (Connection oriented) like below:
SqlDataReader reader = com2.ExecuteReader();
while (reader.Read())
{
int UserId = Convert.ToInt(reader[0]);// or reader["UserID"]
}
reader.Close();
Or you can use DataAdapter (disconnected mode) like:
SqlDataAdapter a = new SqlDataAdapter(com2, connection);
DataTable dt = new DataTable();
a.Fill(dt);
Now your dt.Rows["UserID"] will have the UserID you need.
You may wanna see this: http://www.dotnetperls.com/sqldataadapter
If I understood you correctly, I think the following code might work. Or in the least give you an idea about how you can go about it. Am assuming that you want each student's UserName and Password to default to their StudentID
SqlConnection conUpdate = new SqlConnection(GetConnectionString());
conUpdate.Open();
SqlCommand com2 = new SqlCommand();
com2.Connection = conUpdate;
com2.CommandType = CommandType.Text;
com2.CommandText = "SELECT Students.StudentID, Users.UserID FROM Students, Users " +
"WHERE Students.UserID = Users.UserID";
SqlDataReader reader = com2.ExecuteReader();
if(reader != null)
{
while(reader.Read())
{
SqlCommand com3 = new SqlCommand();
com3.Connection = conUpdate;
com3.CommandType = CommandType.Text;
com3.CommandText = "UPDATE Users SET UserName=#UserName, Password=#Password WHERE UserID=#UserID";
// Assuming that you need both the UserName and Password to default to StudentID
com3.Parameters.AddWithValue("#UserName", reader.GetString(0)); // Assuming StudentID is NVARCHAR
com3.Parameters.AddWithValue("#Password", reader.GetString(0)); // Assuming StudentID is NVARCHAR
com3.Parameters.AddWithValue("#UserID", reader.GetString(1)); // Assuming UserID is NVARCHAR
com3.ExecuteNonQuery();
}
reader.Close();
}
conUpdate.Close();