Description not based on database - c#

I can retrieve data from the database and it works now, but only on the first line (both description and code are correct and based on the database).
On the second line, the description is not based on the database, however it display the description for the first line, even though the code for first and second line are different. How do I fix that?
Here is some code:
private void UpdateDatas()
{
int codeValue = 0;
OleDbDataReader dReader;
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
OleDbCommand cmd = new OleDbCommand(
"SELECT [Description], [Price] FROM [Data] WHERE [Code]=#Code", conn);
cmd.Parameters.Add("Code", System.Data.OleDb.OleDbType.Integer);
cmd.Parameters.Add("Code", System.Data.OleDb.OleDbType.Integer);
if (int.TryParse(this.textBoxCodeContainer[0][0].Text, out codeValue))
{
cmd.Parameters["Code"].Value = codeValue;
}
else if (int.TryParse(this.textBoxCodeContainer[0][1].Text, out codeValue))
{
cmd.Parameters["Code"].Value = codeValue;
}
else
{
MessageBox.Show("Error");
}
dReader = cmd.ExecuteReader();
while (dReader.Read())
{
if (textBoxCodeContainer[0][0].TextLength != 0)
{
this.textBoxDescContainer[0][0].Text = dReader["Description"].ToString();
this.textBoxSubTotalContainer[0][0].Text = dReader["Price"].ToString();
}
if (textBoxCodeContainer[0][1].TextLength != 0)
{
this.textBoxDescContainer[0][1].Text = dReader["Description"].ToString();
this.textBoxSubTotalContainer[0][1].Text = dReader["Price"].ToString();
}
}
dReader.Close();
conn.Close();
}
Here is the image:
Here is the image of the database:

That's because you processes first record twice in your loop, for both text boxes. Try this as a quick fix:
int index = 0;
while (dReader.Read())
{
if (textBoxCodeContainer[0][index].TextLength != 0)
{
this.textBoxDescContainer[0][index].Text = dReader["Description"].ToString();
this.textBoxSubTotalContainer[0][index].Text = dReader["Price"].ToString();
}
index += 1;
}
The second problem, is that you add two values for one parameter (Code) in your query, so the result of the select will contain only one row. You should you the "IN" SQL keyword. The second quick fix would concern your query:
var query = "SELECT [Description], [Price] FROM [Data] WHERE [Code] IN (";
if (int.TryParse(this.textBoxCodeContainer[0][0].Text, out codeValue))
{
query = query + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][1].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
query = query + ")";
OleDbCommand cmd = new OleDbCommand(query, conn);
dReader = cmd.ExecuteReader();
How to parametrize the query with the "IN" clause is another problem - this is just a quick fix to make this work.

Related

Adding new data when item is not available

Im very new on programming and Im having a difficult time thinking on how can I add new Item when Item Code does not exist on the database. It seems to run smoothly until I add else statement. here my code:
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
con.Open();
OleDbCommand command = new OleDbCommand(#"Select * from TblInventory where ItemCode=itemcode");
command.Connection = con;
command.Parameters.AddWithValue("#itemcode", txtItem.Text);
OleDbDataReader reader = command.ExecuteReader();
if (reader.HasRows == true)
{
OleDbCommand cmd = new OleDbCommand(#"Update TblInventory set Quantity = Quantity + #Quantity
WHERE ItemCode = #itemcode");
cmd.Connection = con;
cmd.Parameters.AddWithValue("#Quantity",Convert.ToInt32(txtQuantity.Text));
cmd.Parameters.AddWithValue("#itemcode", txtItem.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Saved !");
}
else
{
OleDbCommand cmdInsert = new OleDbCommand(#"insert into TblInventory (ItemCode,ProductName,Quantity)
values ('" + txtItem.Text + "','" + txtProduct.Text + "','" + txtQuantity.Text + "')");
cmdInsert.Connection = con;
cmdInsert.ExecuteNonQuery();
MessageBox.Show("New Data Added");
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
One of the best way to find existing record in database is to count the number of given record criteria.
OleDbCommand command = new OleDbCommand(#"Select COUNT(ItemCode) from
TblInventory where ItemCode= #itemcode");
Then use ExecuteScalar() instead of ExecuteReader()
Int32 count = (int32) command.ExecuteScalar();
ExecuteScalar() returns the first column of the first row of your query result which is the count of your itemCode. You can read in this link for more information.
Then you can do the simple conditional logic.
if (count > 0) // means that itemCode has 1 or more record count found in the db.
{
// Do the update logic here..
}
else
{
// Do the insert logic here...
}
I already found the answer.
FROM THIS:
OleDbCommand command = new OleDbCommand(#"Select * from TblInventory where ItemCode=itemcode");
TO THIS:
OleDbCommand command = new OleDbCommand(#"Select * from TblInventory where ItemCode='" + txtItem.Text + "'");

Retrieving ID while having only user_name

I'm trying to make a private message system.
What I have so far.
- checking if player exists with the name from textbox, if not, error shows up.
Now, I'm trying to insert it to the table. The problem is that the table have 2 colums
to_user_id
from_user_id
And becasuse I'm using a textbox to enter the name of the user, I dont how to retrieve to_user_id from users table while having only name.
this is my code
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connect"].ToString());
conn.Open();
SqlCommand cmdd = new SqlCommand();
cmdd.CommandText = "select * from [users]";
cmdd.Connection = conn;
SqlDataReader rd = cmdd.ExecuteReader();
while (rd.Read())
{
if (rd[1].ToString() == TextBox_To.Text)
{
flag = false;
break;
}
}
conn.Close();
if (flag == true)
{
Label1.Visible = true;
Label1.Text = "User does not exist";
}
else if(flag == false)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connect"].ToString()))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = #"INSERT INTO messages (message_title, message_content, to_user_id, from_user_id, message_date)
VALUES (#title, #content, #to, #from, #date)";
cmd.Parameters.AddWithValue("#title", TextBox_Title.Text);
cmd.Parameters.AddWithValue("#content", TextBox_Msg.Text.Replace("\n", "<br/>"));
cmd.Parameters.AddWithValue("#to", TextBox_To.Text);
cmd.Parameters.AddWithValue("#date", DateTime.Now);
cmd.Parameters.AddWithValue("#from", Session["id"].ToString());
con.Open();
cmd.ExecuteNonQuery();
}
}
Of course I got an error
Conversion failed when converting the nvarchar value 'username' to data type int.
#edit,
#cordan I tried this
DECLARE #user_id = (SELECT id FROM users WHERE user_login=#to );
INSERT INTO messages (message_title, message_content, to_user_id, from_user_id, message_date)
VALUES (#title, #content, #user_id, #from, #date);
cmd.Parameters.AddWithValue("#to", TextBox_To.Text);
got this error
Incorrect syntax near '='.
Must declare the scalar variable "#user_id".
This bit here is a huge NO!!
SqlCommand cmdd = new SqlCommand();
cmdd.CommandText = "select * from [users]";
cmdd.Connection = conn;
SqlDataReader rd = cmdd.ExecuteReader();
while (rd.Read())
{
if (rd[1].ToString() == TextBox_To.Text)
{
flag = false;
break;
}
}
conn.Close();
You are selecting every single user from the users table, just to determine if the one you're trying to find exists.
Aside from the fact that you could almost certainly just add:
if (rd[1].ToString() == TextBox_To.Text)
{
foundUserId = (int)rd[0]; // I'm assuming the first column in users is the Id - it probably is
flag = false;
break;
}
DONT DO THAT!!
Instead, you should just be looking for the one username you're interested in
SqlCommand cmdd = new SqlCommand();
cmdd.CommandText = "select top 1 Id from [users] where username=#username";
cmdd.Parameters.AddWithValue("#username",username);
cmdd.Connection = conn;
SqlDataReader rd = cmdd.ExecuteReader();
var userId = 0;
if(rd.Read())
{
userId = (int)rd[0];
}
conn.Close();
if (userId == 0)
{
Label1.Visible = true;
Label1.Text = "User does not exist";
return;
}
else
.... // userId holds the users Id
...
cmd.Parameters.AddWithValue("#to", userId);

Implement search / lookup in Win Form

I have a 4 text boxes on a win form. [First Name, Last Name, Job, Description.]
I have one table.
I have the dataset and a data table configured and I can navigate the records.
I want to know how can I search based on first name, obtain the data from dataset/table and display the info based on what is in the text box.
how do I do this such as, obtain the row, "inc" where the
txtFirstName = ds.Tables[0].Column[1]
Then I can:
DataRow row = ds.Tables[0].Rows[inc];
txtFirstName.Text = row[1];
txtSurname.Text = row[2];
txtJobTitle.Text = row[3];
txtDepartment.Text = row[4];
sorry, found the solution.
First I created a search method which returned the row...
private int first_name_search(string fname)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
if ((string)ds.Tables[0].Rows[i]["first_name"] == fname)
{
send = i;
//result stuff
break;
}
}
// return result;
return send;
}
I used this method in the Search button click method and displayed the data...
In a function that return a string[]:
string[number_of_infos] infos = null;
connection = new SqlConnection(connectionString);
connection.Open();
cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM your_table WHERE first_name = " + your_first_name;
cmd.Connection = connection;
rdr = cmd.ExecuteReader();
if(rdr.Read())
{
infos[0] = rdr["Surname"].ToString();
infos[1] = rdr["JobTitle"].ToString();
infos[2] = rdr["Department"].ToString();
}
cmd.Dispose();
connection.Close();
return infos;
Direct in your form:
connection = new SqlConnection(connectionString);
connection.Open();
cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM your_table WHERE first_name = " + your_first_name;
cmd.Connection = connection;
rdr = cmd.ExecuteReader();
if(rdr.Read())
{
txtSurname.Text = rdr["Surname"].ToString();
txtJobTitle.Text = rdr["JobTitle"].ToString();
txtDepartment.Text = rdr["Department"].ToString();
}
cmd.Dispose();
connection.Close();
return infos;
Else if you want to get the row infos:
foreach(DataGridViewRow row in your_DGV.Rows)
if(row["FirstName"].Value.ToString() == txtFirstName.Text)
{
txtSurname.Text = row["Surname"].Value.ToString();
txtJobTitle.Text = row["JobTitle"].Value.ToString();
txtDepartment.Text = row["Department"].Value.ToString();
break;
}
FYI, you can use LINQ extensions to do this:
var tbl = ds.Tables[0].AsEnumerable();
return tbl.Where(p => p["first_name"] == fname).FirstOrDefault();
Edit: To select all matching rows from the DataTable:
var results = from row in tbl.AsEnumerable()
where row["first_name"] == fname
select row;

Updating data to the database did not work

I got the problem. I want to update the data to the database, but the database won't update.
Here is the code:
else if (firstForm.textBox1.Text == "Seranne")
{
string query = "SELECT [Quantity], [Description], [Price] FROM [Seranne] WHERE [Code] IN (";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
if (int.TryParse(this.textBoxCodeContainer[0].Text, out codeValue))
{
query = query + codeValue.ToString();
}
for (int i = 1; i < 17; i++)
{
if (int.TryParse(this.textBoxCodeContainer[i].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
}
query = query + ")";
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.Parameters.Add("Code", System.Data.OleDb.OleDbType.Integer);
cmd.Parameters.Add("Quantity", System.Data.OleDb.OleDbType.Integer);
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
while (dReader.Read())
{
if (textBoxCodeContainer[index].TextLength != 0)
{
this.textBoxQuantityContainer[index].Maximum = Convert.ToDecimal(dReader["Quantity"].ToString());
this.textBoxDescContainer[index].Text = dReader["Description"].ToString();
this.textBoxSubTotalContainer[index].Text = dReader["Price"].ToString();
}
if (textBoxQuantityContainer[index].Value != 0 && textBoxQuantityContainer[index].Value >= Convert.ToDecimal(dReader["Quantity"].ToString()))
{
newVal = textBoxQuantityContainer[index].Value - Convert.ToDecimal(dReader["Quantity"].ToString());
cmd = new OleDbCommand("UPDATE [Seranne] SET [Quantity] ='" + newVal + "' WHERE [Code] IN ('");
}
index += 1;
}
conn.Close();
dReader.Close();
}
}
private void UpdateQuantity()
{
System.Media.SoundPlayer sound = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Notify.wav");
sound.Play();
MessageBox.Show("Updated Successfully", "Success");
}
private void button1_Click(object sender, EventArgs e)
{
UpdateQuantity();
}
EDIT: (The function UpdateQuantity in below is when the user click Update button) and i am getting an error when i click the Update button, here is the error: Syntax error (missing operator) in query expression '[Code] IN ('.
private void UpdateQuantity()
{
int index = 0;
int codeValue = 0;
string query = "SELECT [Quantity], [Description], [Price] FROM [Seranne] WHERE [Code] IN (";
OleDbConnection conn = new OleDbConnection(connectionString);
OleDbDataReader dReader;
OleDbCommand cmd = new OleDbCommand(query, conn);
conn.Open();
cmd.Parameters.Add("Quantity", System.Data.OleDb.OleDbType.Integer);
dReader = cmd.ExecuteReader();
if (textBoxQuantityContainer[index].Value != 0 && textBoxQuantityContainer[index].Value >= Convert.ToDecimal(dReader["Quantity"].ToString()))
{
cmd = new OleDbCommand("UPDATE [Seranne] SET [Quantity] ='" + newVal + "' WHERE [Code] IN (", conn);
if (int.TryParse(this.textBoxCodeContainer[0].Text, out codeValue))
{
query = query + codeValue.ToString();
}
for (int i = 1; i < 17; i++)
{
if (int.TryParse(this.textBoxCodeContainer[i].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
}
query = query + ")";
newVal = textBoxQuantityContainer[index].Value - Convert.ToDecimal(dReader["Quantity"].ToString());
cmd.ExecuteNonQuery();
System.Media.SoundPlayer sound = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Notify.wav");
sound.Play();
MessageBox.Show("Updated Successfully", "Success");
}
index += 1;
dReader.Close();
conn.Close();
}
private void button1_Click(object sender, EventArgs e)
{
UpdateQuantity();
}
Above code all worked, excepts for updating the Quantity to the database. What I mean is, I set the Quantity in database to 100, when I set Quantity to 10 in my program and update it, the database should be update the Quantity to 90 (because 100 - 10), but it is still at 100.
Could I wrong somewhere?
Here is the link of the screenshots: (ScreenShot 1) https://www.dropbox.com/s/rph5iuh371rc9ny/Untitled.png
(ScreenShot 2) https://www.dropbox.com/s/5q8pyztqy7ejupy/Capture.PNG
In the Screenshot 1, I already set the quantity to 10 and the messagebox show that the data has been updated successfully and the data in the database supposed to be 90 (because 100-10). But, in the Screenshot 2 where the database is, the Quantity still at 100.
Thanks in advance!
Your update query
cmd = new OleDbCommand("UPDATE [Seranne] SET [Quantity] ='" + newVal + "' WHERE [Code] IN ('");
doesn't appear to be completed in the code you have posted. My guess is that you are getting a syntax error which your code is not trapping and displaying.

Syntax error (missing operator) in query expression '[Code] IN('

I am getting an error while updating the data, the error says: "Syntax error (missing operator) in query expression '[Code] IN('."
Here is the code where i am getting an error at:
OleDbDataReader dReader = cmd.ExecuteReader();
Here is the full code of the function that the error is appear:
private void UpdateQuantity()
{
int index = 0;
string command = "UPDATE [Seranne] SET [Quantity] ='" + newVal + "' WHERE [Code] IN(";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
OleDbCommand cmd = new OleDbCommand(command, conn);
cmd.Parameters.Add("Quantity", System.Data.OleDb.OleDbType.Integer);
OleDbDataReader dReader = cmd.ExecuteReader();
while (dReader.Read())
{
if (textBoxQuantityContainer[index].Value != 0 && textBoxQuantityContainer[index].Value >= Convert.ToDecimal(dReader["Quantity"].ToString()))
{
newVal = Convert.ToDecimal(dReader["Quantity"].ToString()) - textBoxQuantityContainer[index].Value;
}
System.Media.SoundPlayer sound = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Notify.wav");
sound.Play();
MessageBox.Show("Updated Successfully", "Success");
index += 1;
}
conn.Close();
dReader.Close();
}
Here is the previous code where the query expression "Code IN":
string query = "SELECT [Quantity], [Description], [Price] FROM [Seranne] WHERE [Code] IN (";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
if (int.TryParse(this.textBoxCodeContainer[0].Text, out codeValue))
{
query = query + codeValue.ToString();
}
for (int i = 1; i < 17; i++)
{
if (int.TryParse(this.textBoxCodeContainer[i].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
}
query = query + ")";
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.Parameters.Add("Code", System.Data.OleDb.OleDbType.Integer);
cmd.Parameters.Add("Quantity", System.Data.OleDb.OleDbType.Integer);
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
while (dReader.Read())
{
if (textBoxCodeContainer[index].TextLength != 0)
{
this.textBoxQuantityContainer[index].Maximum = Convert.ToDecimal(dReader["Quantity"].ToString());
this.textBoxDescContainer[index].Text = dReader["Description"].ToString();
this.textBoxSubTotalContainer[index].Text = dReader["Price"].ToString();
}
index += 1;
}
conn.Close();
dReader.Close();
Thanks a bunch!
OK, just keep your code and change this:
for (int i = 1; i < 17; i++) {
if (int.TryParse(this.textBoxCodeContainer[i].Text, out codeValue))
{
query = query + codeValue + ",";
}
}
query = query.TrimEnd(',') + ")";
before proceed you better create integer list out of textBoxCodeContainer values, say it as integers
then
string command = "UPDATE [Seranne] SET [Quantity] =? WHERE [Code] IN(" + string.Join(", " , integers) +")";
Generate integer list as below
List<int> integers = new List<int>();
foreach (var tb in textBoxCodeContainer)
{
int codeValue;
if (int.TryParse(tb.Text, out codeValue))
{
integers.Add(codeValue);
}
}

Categories

Resources