I have a C# application that submits information to an Access database. I fill in three required boxes , and click "Submit". The script should respond in the following manner when the use clicks the button:
Step 1. Look into database Table A, to see if the value in textBox1 exists in the database.
Step 2. If the value exists, add the values of textBox1, textBox2, and textBox3 into database Table B columns, respectively.
Step 3. If any one of the three text boxes are left blank, display a message.
Step 4. If the value in textBox1 is not in the database table, display a message. (eventually, I plan the replace the message with a default population of the database fields)
THE PROBLEM: When I run the program, in any of the above cases, the result is Step number 4 above. It seems to skip the first "if" statement, and jumping right to the "else" outcome.
Any help resolving this, would be greatly appreciated! The "Private Void "code is below.
Thanks in advance.
private void button1_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand("select * from script_Orders where cust_Name = #UserID", vcon);
OleDbParameter param = new OleDbParameter();
param.ParameterName = "#UserID";
param.Value = textBox1.Text;
cmd.Parameters.Add(param);
OleDbDataReader reader = cmd.ExecuteReader();
{
if (reader.HasRows)
{
if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "")
{
MessageBox.Show("You must fill in all fields.");
return;
}
else
{
OleDbCommand dbCommand;
OleDbDataReader dbReader;
new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;data source=C:\Search\Database.accdb");
dbCommand = new OleDbCommand("select count(*) as Record_Count from script_received", vcon);
dbReader = dbCommand.ExecuteReader();
if (dbReader.Read() == true)
rowCount = dbReader["Record_Count"].ToString();
else
return;
var date = DateTime.Now.ToString("MM/dd/yyyy");
{
using (OleDbCommand command = new OleDbCommand("INSERT INTO script_Received (script, qty, emp_id, received_Date) VALUES (#script,#qty,#emp_Id,#rec_date)"))
{
command.CommandType = CommandType.Text;
command.Parameters.Add("#script", OleDbType.Integer).Value = textBox1.Text;
command.Parameters.Add("#qty", OleDbType.VarChar).Value = textBox2.Text;
command.Parameters.Add("#emp_id", OleDbType.VarChar).Value = textBox3.Text;
command.Parameters.Add("#rec_date", OleDbType.Date).Value = date;
command.Connection = vcon;
command.ExecuteNonQuery();
}
this.textBox1.Clear();
this.textBox2.Clear();
this.textBox1.Focus();
}
}
}
else
{
MessageBox.Show("The value of textBox1 is not in the orders table");
return;
}
}
}
If it jumps to the else of if(reader.HasRows) without throwing any exceptions, then reader must not be null, and it's HasRows property must be false. That means your query executed successfully but returned no rows.
You might try running the select statement by hand, which might help you understand what's wrong. Most likely, you're typing something in the textbox that doesn't match any of the cust_name values.
Related
Since yesterday I am trying to get this value (see image), I have tried to use "mysqlreader, executescalar and more", but I cannot get the number of lines.
What I want to do is this:
If the result is 0 it does nothing, if equal to 1 it must show an image, if greater than 1 it must show another image
ex code 1
private void patient()
{
if (OpenEventMissionData.Rows.Count != 0)
{
foreach (DataGridViewRow row in OpenEventMissionData.Rows)
{
string idevent = row.Cells[1].Value.ToString();
string sql = "SELECT COUNT(*) FROM patient INNER JOIN event WHERE patient.ID_EVENT = " + "'" + idevent + "'" + "AND evento.EVENT_OPEN = 1;";
MySqlConnection connection = new MySqlConnection();
connection.ConnectionString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
MySqlCommand cmd = new MySqlCommand(sql, connection);
connection.Open();
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
DataGridViewButtonColumn patient = new DataGridViewButtonColumn();
OpenEventMissionData.Columns.Add(new PatientColumn());
}
}
}
}
I tried adding the code that told me #oldDog, but the result is always 6
ex code 3
NEW EDIT:
In fact 6 lines appear.
phpmyadmin
Your problem here is you are using HasRows. Since you are doing SELECT COUNT(*) you will always have one row which will contain the count, even if the count is zero. Instead you could use:
if (Convert.ToInt32(reader[0]) > 0)
let me explain the idea of my simple project so you can get my question .. I have a multi login page first page is student and the other admin in the login page the values are set as select from and in the student it is set as insert into so the problem is the student will enter his window and make a request and it will go back to the database but the problem that i'm facing now i can't tell which student made the request ! i need somehow to take the column username from the login table which is set as select from and make it into the insert into in the student table ! i have no idea how to do that but i hope you get my question i will put the coding for the reference and excuse my rookie question and coding .
if (sqlCon.State == ConnectionState.Closed)
sqlCon.Open();
string query = "SELECT count (1) FROM Login WHERE Username=#Username AND password=#password AND usertype=#usertype";
SqlCommand sqlCmd = new SqlCommand(query, sqlCon);
sqlCmd.CommandType = CommandType.Text;
sqlCmd.Parameters.AddWithValue("#Username", txtUsername.Text);
sqlCmd.Parameters.AddWithValue("#password", txtPassword.Text);
if (checkbox1.IsChecked == true)
sqlCmd.Parameters.AddWithValue("#usertype", checkbox1.Content.ToString());
else if (checkbox2.IsChecked == true)
sqlCmd.Parameters.AddWithValue("#usertype", checkbox2.Content.ToString());
int count = Convert.ToInt32(sqlCmd.ExecuteScalar());
if (count == 1)
{
if ((bool)checkbox1.IsChecked == true)
{
MainWindow Dashboard = new MainWindow();
Dashboard.Show();
MessageBox.Show("You're logged in as an Admin");
this.Close();
}
if ((bool)checkbox2.IsChecked == true)
{
Student stu = new Student();
stu.Show();
MessageBox.Show("You're logged in as a Student");
this.Close();
}
}
///the Student window
private void button_Click(object sender, RoutedEventArgs e)
{
using (var Con = new SqlConnection(#"Data Source = test\SQLEXPRESS; Initial Catalog =Log-In; Integrated Security = True"))
{
Con.Open();
var table = "INSERT INTO Student(DepartureCiry,ArrivalCity,DateOfDeparture,DateOfReturn)VALUES(#DepartureCiry,#ArrivalCity,#DateOfDeparture,#DateOfReturn)";
using (var cmd = new SqlCommand(table, Con))
{
cmd.Parameters.AddWithValue("#DepartureCiry", fromtxt.Text);
cmd.Parameters.AddWithValue("#ArrivalCity", Totxt.Text);
cmd.Parameters.AddWithValue("#DateOfDeparture", date_time_picker.Text);
cmd.Parameters.AddWithValue("#DateOfReturn", date_time_picker1.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Data inserted suckssfully");
You need to change your query to be
string query = "SELECT Username FROM Login WHERE Username=#Username AND password=#password AND usertype=#usertype";
Instead of selecting only the count(1) you select the actual row (in my case I only select the Username column as you only need it).
Then instead of calling ExecuteScalar on the sql command you need to use a SqlDataReader to actually retrieve the row.
SqlDataReader reader = sqlCmd.ExecuteReader();
if (reader.HasRows)
{
string userName;
while (reader.Read())
{
userName = ((IDataRecord)reader)["Username"].ToString();
break;
}
}
From here you have your student name from the Login table.
However my observation is that this name will actually be the same as the txtUsername.Text.
I think you need some other columns from the Students table, but generally this is the way to retrieve them - user SqlDataReader, and retrieve the column with the ((IDataRecord)reader)["MyColumnName"].
Some additional notes:
I use HasRows property on the reader to see if it has a match instead of getting the count. And I imply that you have unique Usernames in the database (otherwise you have to loop the reader to see how many rows it return).
So I'm having this :
Conn.Open();
SqlCommand Comm3 = new SqlCommand("SELECT answer" + " FROM answers" + " WHERE id_answer=5" , Conn);
SqlDataReader DR3 = Comm3.ExecuteReader();
And there is multiple results,how can I now move each of them in diffrent textbox (i already created textboxes? Till now i only managed to get same result into them.
this is normally how i do it....
SqlConnection cn = new SqlConnection("my connection string");
cn.Open();
string sql = "select * from table where column = whatever";
using (SqlCommand cmd = new SqlCommand(sql,cn))
{
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
myTextBox1.Text = (string)dr["Column1"];
myTextBox2.Text = (string)dr["Column2"];
myTextBox3.Text = (string)dr["Column3"];
}
dr.Close();
}
cn.Close();
just make sure you are aiming the right column name while looping through them, and cast correctly.
You need to loop through each of the item in the Database table. Think of a foreach loop, where you simply just go through each item and work on it similarly.
Here is a sample for that,
// Create new SqlDataReader object and read data from the command.
using (SqlDataReader reader = command.ExecuteReader())
{
// while there is another record present
while (reader.Read())
{
// write the data on to the screen
textBox.Text = reader[0];
}
}
This will add the value of reader's first column (answer) to the textBox. Now make sure you're calling correct textBox to add the value to.
http://www.codeproject.com/Articles/823854/How-to-connect-SQL-Database-to-your-Csharp-program Do give this article a read.
This is my code:
private void CostList_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'lSEStockDataSet.CostPrice' table. You can move, or remove it, as needed.
this.costPriceTableAdapter.Fill(this.lSEStockDataSet.CostPrice);
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Data Source=tcp:SHEN-PC,49172\\SQLEXPRESS;Initial Catalog=LSEStock;Integrated Security=True";
con.Open();
DataGridView datagridview1 = new DataGridView();
String retrieveData = "SELECT CostID, SupplierName, CostPrice FROM CostPrice WHERE PartsID ='" + textBox1.Text + "'";
SqlCommand cmd = new SqlCommand(retrieveData, con);
int count = cmd.ExecuteNonQuery();
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataGridView1.DataSource = dt;
con.Close();
}
private void button1_Click(object sender, EventArgs e)
{
if (dataGridView1.Rows.Count > 0)
{
int nRowIndex = dataGridView1.Rows.Count-1;
if (dataGridView1.Rows[nRowIndex].Cells[2].Value != null)
{
textBox2.Text = Convert.ToString(dataGridView1.Rows[nRowIndex].Cells[2].Value);
}
else
{
MessageBox.Show("NULL");
}
}
}
It shows NULL when i clikc the button, what is the problem here? I have 3 columns there, i want to get the data of the 3rd column of the last row, but it shows NULL but there is data in the specified cell. Anyone knows how to solve this problem?
Instead of subtracting one from the row count, try subtracting two. Subtracting one is giving you the zero-based index of the "add" row, which indeed has a null value in the last column.
int nRowIndex = dataGridView1.Rows.Count-2;
By subtracting 2 from the count, you will get the zero-based index of the last row with actual data in it. I think this is what you are looking for.
As an aside, you will likely want to parameterize your SQL query, something like this:
String retrieveData = "SELECT CostID, SupplierName, CostPrice FROM CostPrice WHERE PartsID = #inPartsID";
SqlCommand cmd = new SqlCommand(retrieveData, con);
cmd.Parameters.Add(new SqlParameter("#inPartsID", textBox1.Text));
This will make your query more reliable (what happens if there is a single quote character in textBox1) and your data more secure (evil-doers can use SQL injection to cause harm to your database or get data out of it that they shouldn't).
i m trying to edit the values in database through textboxes in ASP.
first i retrived the values from database and set those values to the value property of textboxes on the form so that user can see the old values.
now, i want him to enter new values in the same textboxes and when he click on update the new values should be updated in the database.
can any one tell what i have to do to get those new values????
when to submit the form????
the code:
protected void Button2_Click(object sender, EventArgs e)
{
string MachineGroupName = TextBox2.Text;
string MachineGroupDesc = TextBox3.Text;
int TimeAdded = DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second;
if (MachineGroupName == "" || MachineGroupDesc == "")
{
Label2.Text = ("Please ensure all fields are entered");
Label2.Visible = true;
}
else
{
System.Data.SqlClient.SqlConnection dataConnection = new SqlConnection();
dataConnection.ConnectionString =
#"Data Source=JAGMIT-PC\SQLEXPRESS;Initial Catalog=SumooHAgentDB;Integrated Security=True";
System.Data.SqlClient.SqlCommand dataCommand = new SqlCommand();
dataCommand.Connection = dataConnection;
//tell the compiler and database that we're using parameters (thus the #first, #last, #nick)
dataCommand.CommandText = ("UPDATE [MachineGroups] SET ([MachineGroupName]=#MachineGroupName,[MachineGroupDesc]=#MachineGroupDesc,[TimeAdded]=#TimeAdded) WHERE ([MachineGroupID]= #node)");
//add our parameters to our command object
dataCommand.Parameters.AddWithValue("#MachineGroupName", MachineGroupName);
dataCommand.Parameters.AddWithValue("#MachineGroupDesc", MachineGroupDesc);
dataCommand.Parameters.AddWithValue("#TimeAdded", TimeAdded);
dataConnection.Open();
dataCommand.ExecuteNonQuery();
dataConnection.Close();
}
You're not providing the #node parameter. so you should get an exception. Also change your sql statement like that without parenthesis :
long MachineGroupID = Convert.ToInt64(Request.QueryString["node"]);
dataCommand.CommandText = "UPDATE [MachineGroups] SET [MachineGroupName]=#MachineGroupName,[MachineGroupDesc]=#MachineGroupDesc,[TimeAdded]=#TimeAdded WHERE [MachineGroupID]= #MachineGroupID";
//add our parameters to our command object
dataCommand.Parameters.AddWithValue("#MachineGroupName", MachineGroupName);
dataCommand.Parameters.AddWithValue("#MachineGroupDesc", MachineGroupDesc);
dataCommand.Parameters.AddWithValue("#TimeAdded", TimeAdded);
dataCommand.Parameters.AddWithValue("#MachineGroupID", MachineGroupID);
EDIT : As you posted your insert page, your table should have an ID column to identify your record uniquely. As I see in your update SQL youe ID column's name is MachineGroupID. So to update your record, you should provide MachineGroupID as #node parameter. try to get this MachineGroupID value in your event and pass it into your Command.
long MachineGroupID = Convert.ToInt64(Request.QueryString["node"]);
dataCommand.CommandText = "UPDATE [MachineGroups] SET
[MachineGroupName]=#MachineGroupName,[MachineGroupDesc]=#MachineGroupDesc,
[TimeAdded]=#TimeAdded WHERE [MachineGroupID]= #MachineGroupID",cn; //add our parameters to our command object
dataCommand.Parameters.AddWithValue("#MachineGroupName", MachineGroupName);
dataCommand.Parameters.AddWithValue("#MachineGroupDesc", MachineGroupDesc);
dataCommand.Parameters.AddWithValue("#TimeAdded", TimeAdded);
dataCommand.Parameters.AddWithValue("#MachineGroupID", MachineGroupID);
example :
SqlCommand cmdup = new SqlCommand("UPDATE [port1] SET [prt1]=#prt1 WHERE [no]= 1", cn);
cmdup.Parameters.Add("#prt1", TextBox1.Text);
cmdup.ExecuteNonQuery();
I think this may help your case, mention Connection at the last of your update command
ok i have the insert page which is working fine with this code.......
protected void Button2_Click(object sender, EventArgs e)
{
string MachineGroupName = TextBox2.Text;
string MachineGroupDesc = TextBox3.Text;
int TimeAdded = DateTime.Now.Hour+DateTime.Now.Minute+DateTime.Now.Second;
if (MachineGroupName == "" || MachineGroupDesc == "")
{
Label1.Text = ("Please ensure all fields are entered");
Label1.Visible = true;
}
else
{
System.Data.SqlClient.SqlConnection dataConnection = new SqlConnection();
dataConnection.ConnectionString =
#"Data Source=JAGMIT-PC\SQLEXPRESS;Initial Catalog=SumooHAgentDB;Integrated Security=True";
System.Data.SqlClient.SqlCommand dataCommand = new SqlCommand();
dataCommand.Connection = dataConnection;
//tell the compiler and database that we're using parameters (thus the #first, #last, #nick)
dataCommand.CommandText = ("INSERT [MachineGroups] ([MachineGroupName],[MachineGroupDesc],[TimeAdded]) VALUES (#MachineGroupName,#MachineGroupDesc,#TimeAdded)");
//add our parameters to our command object
dataCommand.Parameters.AddWithValue("#MachineGroupName", MachineGroupName);
dataCommand.Parameters.AddWithValue("#MachineGroupDesc", MachineGroupDesc);
dataCommand.Parameters.AddWithValue("#TimeAdded", TimeAdded);
dataConnection.Open();
dataCommand.ExecuteNonQuery();
dataConnection.Close();
}