Adding new data when item is not available - c#

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 + "'");

Related

How do you read a database table and display it in a textbox

I am creating a basic app for adding and displaying customer information using windows forms in visual studio. i have set it up so i am able to display the contents of the database in a gridview and also add to the database which you can see the code for below. what i am stuck on at the moment is updating the customers information. I want to search the database by customerID which will be entered by the user in a textbox, and display that specific customers details into their relevent textboxes which i can then edit and save.
using (SQLiteCommand cmd = conn.CreateCommand())
{
// adds customers details to the database
cmd.CommandText = #"INSERT INTO customer (title, " + "firstname, " + "lastname, " + "dob, " + "nicode, " + "email, " + "password, " + "allowance) VALUES (#setTitle, #setFirstname, #setLastname, #setDOB, #setNICode, #setEmail, #setPassword, #setAllowance)";
cmd.Parameters.AddWithValue("setTitle", cb_title.Text);
cmd.Parameters.AddWithValue("setFirstname", txtFirst_Name.Text);
cmd.Parameters.AddWithValue("setLastname", txtSurname.Text);
cmd.Parameters.AddWithValue("setDOB", dtp_DOB.Text);
cmd.Parameters.AddWithValue("setNICode", txtNI_Code.Text);
cmd.Parameters.AddWithValue("setEmail", txtEmail.Text);
cmd.Parameters.AddWithValue("setPassword", txtPassword.Text);
cmd.Parameters.AddWithValue("setAllowance", txtAllowance.Text);
int recordsChanged = cmd.ExecuteNonQuery();
MessageBox.Show("Customer Added");
conn.Close();
Customers customers = new Customers();
customers.Show();
this.Hide();
}
That's what I have for adding a new customer which works fine
using (SQLiteCommand cmd = conn.CreateCommand())
{
// adds customers details to the database
cmd.CommandText = #"UPDATE customer SET (title, " + "firstname, " + "lastname, " + "dob, " + "nicode, " + "email, " + "password, " + "allowance) VALUES (#setTitle, #setFirstname, #setLastname, #setDOB, #setNICode, #setEmail, #setPassword, #setAllowance) WHERE custid = #recd";
cmd.Parameters.AddWithValue("title", cb_title_update.Text);
cmd.Parameters.AddWithValue("firstname", txtFirst_Name_update.Text);
cmd.Parameters.AddWithValue("lastname", txtSurname_update.Text);
cmd.Parameters.AddWithValue("dob", dtp_DOB_update.Text);
cmd.Parameters.AddWithValue("nicode", txtNI_Code_update.Text);
cmd.Parameters.AddWithValue("email", txtEmail_update.Text);
cmd.Parameters.AddWithValue("password", txtPassword_update.Text);
cmd.Parameters.AddWithValue("allowance", txtAllowance_update.Text);
cmd.Parameters.AddWithValue("recd", Convert.ToInt32(txtSearch.Text));
int recordsChanged = cmd.ExecuteNonQuery();
MessageBox.Show("Customer Updated");
conn.Close();
Customers customers = new Customers();
customers.Show();
this.Hide();
}
And that's the code I have so far for updating the database, but I can not figure out how to retrieve the customer data and display it into the textboxes, any help or guidance would be appreciated
Your Update statement is not correct. Try the following.
cmd.CommandText =#"UPDATE customer
SET title = #setTitle,
firstname = #setFirstname,
lastname = #setLastname
dob = #setDOB,
nicode = #setNICode,
email = #setEmail,
password = #setPassword,
allowance = #setAllowance
WHERE custid = #recd";
It is a bit different from an Insert. Each field is set to a new value. You don't need all that concatenation. This is a literal string.
Of course, in a real application you would NEVER store passwords as plain text.
To get the value of a certain column from a certain row, you can try to call method SqlCommand.ExecuteReader.
Here assume you want to get the the customer password.
string connectionstring = #"connectin string";
private void btnSearch_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(connectionstring))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "Select * from customer where customerID = #cusID";
cmd.Parameters.AddWithValue("#cusID", textBoxID.Text);
conn.Open();
try
{
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow);
if (reader.HasRows)
{
if (reader.Read())
{
// get password column value
textBoxPWD.Text = reader["password"].ToString();
}
}
else
{
Console.WriteLine("no such record");
}
}
catch (Exception ex)
{
Console.WriteLine("\nError:\n{0}", ex.Message);
}
}
}
As to update the record,
private void btnUpdate_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(connectionstring))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "UPDATE customer SET password = #cusPWD WHERE customerID = #cusID";
cmd.Parameters.AddWithValue("#cusID", textBoxID.Text);
cmd.Parameters.AddWithValue("#cusPWD", textBoxPWD.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
}

Data type mismatch in criteria expression(Convert.ToInt32(cmd.ExecuteScalar());)

I am trying to Display a name in the textbox from the database if the ID entered by the user matches the record in the MS ACCESS DATABASE.
I'm getting the error Data type mismatch in criteria expression at the line int count = Convert.ToInt32(cmd.ExecuteScalar());
The following is my aspx.cs code-
protected void Button1_Click(object sender, EventArgs e)
{
clear();
idcheck();
DataTable dt = new DataTable();
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\dfg\fd\Visual Studio 2010\WebSites\WebSite21\App_Data\UPHealth.mdb");
con.Open();
str = "SELECT [DoctorName] FROM [DoctorInfo] WHERE DoctorID='" + TextBox1.Text.Trim() + "'";
OleDbCommand cmd = new OleDbCommand(str, con);
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
TextBox2.Text = dr["DoctorID"].ToString();
dr.Close();
con.Close();
}
}
public void idcheck()
{
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\dfg\fd\Visual Studio 2010\WebSites\WebSite21\App_Data\UPHealth.mdb");
con.Open();
str = "SELECT count(DoctorName) FROM [DoctorInfo] WHERE DoctorID='" + TextBox1.Text.Trim() + "'";
OleDbCommand cmd = new OleDbCommand(str, con);
int count = Convert.ToInt32(cmd.ExecuteScalar());
if (count > 0)
{
Label21.Text = "Doctor Name";
}
else
{
Label21.Text = "Id Does not Exist";
}
}
void clear()
{
TextBox2.Text = "";
}
I guess that is because you as passing in an ID, which is usually a numeric value, as a text field:
DoctorID='" + TextBox1.Text.Trim() + "'
Which should be:
DoctorID=" + TextBox1.Text.Trim()
Another problem arises, since you are vulnerable to SQL injection. What if the text box contained 1; delete users? Then your entire users table would be empty. The lesson learned: use parameterized queries!
Then you can express the SQL as:
DoctorID= ?
And add the parameter to the request:
cmd.Parameters.AddWithValue("?", TextBox1.Text.Trim());

MS Access database not updating

Can anybody tell me why my database isn't updating? Here's my code:
protected void editSection_selected(object sender, EventArgs e) {
int index = grdPhone.SelectedIndex;
GridViewRow row = grdPhone.Rows[index+1];
string values = ((DropDownList)sender).SelectedValue;
int tempVal = Convert.ToInt32(values);
int caseage = Convert.ToInt32(keyId);
int value = tempVal;
/*OleDbConnection con = new OleDbConnection(strConnstring);
//string query = "Update Categories set HRS_LEVEL_AMOUNT=" + tempVal + " where parent_id=65 and ID=" + caseage;
string query = "Delete HRS_LEVEL_AMOUNT from Categories where parent_id=65 and id=" + caseage;
OleDbCommand cmd = new OleDbCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
con.Dispose();
cmd.Dispose();
con.Close();
accPhoneNumbers.UpdateCommand = "Update Categories set HRS_LEVEL_AMOUNT=" + tempVal + " where parent_id=65 and ID=" + caseage;
*/
string str = "UPDATE Categories SET HRS_LEVEL_AMOUNT = ? WHERE ID=?";
using (OleDbConnection con = new OleDbConnection(strConnstring))
{
using (OleDbCommand cmd = new OleDbCommand(str, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("HRS_LEVEL_AMOUNT", tempVal);
cmd.Parameters.AddWithValue("ID", caseage);
con.Open();
cmd.ExecuteNonQuery();
}
}
Label1.Text += " editSection Success! (B) " + tempVal;
}
The commented part is my first solution (including the accPhoneNumbers.UpdateCommand).
I really need your help guys.
I hope this can help you:
string str = "UPDATE Categories SET HRS_LEVEL_AMOUNT = #value1 WHERE ID=#value2";
using (OleDbConnection con = new OleDbConnection(strConnstring))
{
using (OleDbCommand cmd = new OleDbCommand(str, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#value1", tempVal);
cmd.Parameters.AddWithValue("#value2", caseage);
con.Open();
cmd.ExecuteNonQuery();
con.close();
}
}
For more information you can visit this video

Data addition and updation in SQL tables

Iam fairly new to SQLClient and all, and iam having a problem with my SQL tables..when ever i run my code, the data, rather than getting updated, attaches itself to the already existing records in the tables..here's my code
SqlConnection conneciones = new SqlConnection(connectionString);
SqlCommand cmd;
conneciones.Open();
//put values into SQL DATABASE Table 1
for (int ok = 0; ok < CleanedURLlist.Length; ok++)
{
cmd = new SqlCommand("insert into URL_Entries values('" + CleanedURLlist[ok] + "' , '" + DateTime.Now + "' , '" + leak + "' )", conneciones);
cmd.ExecuteNonQuery();
}
conneciones.Dispose();
Take a look at these functions, i hope you understand better on update , insert and delete functions..
Code snippets for reading, inserting, updating and deleting a records using asp.net and c# and sql server database
static void Read()
{
try
{
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=sa123";
using (SqlConnection conn =new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT * FROM EmployeeDetails", conn))
{
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("Id = ", reader["Id"]);
Console.WriteLine("Name = ", reader["Name"]);
Console.WriteLine("Address = ", reader["Address"]);
}
}
reader.Close();
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
static void Insert()
{
try
{
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=sa123";
using (SqlConnection conn =new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("INSERT INTO EmployeeDetails VALUES(" +
"#Id, #Name, #Address)", conn))
{
cmd.Parameters.AddWithValue("#Id", 1);
cmd.Parameters.AddWithValue("#Name", "Amal Hashim");
cmd.Parameters.AddWithValue("#Address", "Bangalore");
int rows = cmd.ExecuteNonQuery();
//rows number of record got inserted
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
static void Update()
{
try
{
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=sa123";
using (SqlConnection conn = ew SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("UPDATE EmployeeDetails SET Name=#NewName, Address=#NewAddress WHERE Id=#Id", conn))
{
cmd.Parameters.AddWithValue("#Id", 1);
cmd.Parameters.AddWithValue("#Name", "Munna Hussain");
cmd.Parameters.AddWithValue("#Address", "Kerala");
int rows = cmd.ExecuteNonQuery();
//rows number of record got updated
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
static void Delete()
{
try
{
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=sa123";
using (SqlConnection conn = ew SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("DELETE FROM EmployeeDetails " +
"WHERE Id=#Id", conn))
{
cmd.Parameters.AddWithValue("#Id", 1);
int rows = cmd.ExecuteNonQuery();
//rows number of record got deleted
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
Your code should be inserting new records, but I'm not clear on whether it is not doing that, or you mean to update existing records.
Aside from that, understanding that you are new to working with SQL Server, there are a couple of things you should be aware of.
You should use using to automatically dispose resources. This will also close your connection for you so you don't have open connections hanging around.
You should use parameters to protect against sql injection attacks. Another benefit of using parameters in your case is that you don't need to create new commands for every statement.
For example:
using (var connection = new SqlConnection(connectionString)
using (var command = connection.CreateCommand())
{
command.CommandText = "insert into URL_Entries values(#url, #now, #leak)";
command.Parameters.AddWithValue("#now", DateTime.Now);
command.Parameters.AddWithValue("#lead", leak);
// update to correspond to your definition of the table column
var urlParameter = command.Parameters.Add(new SqlParameter("#url", SqlDbType.VarChar, 100));
connection.Open();
for (int ok = 0; ok < CleanedURLlist.Length; ok++)
{
urlParameter.Value = CleanedURLlist[ok];
command.ExecuteNonQuery();
}
}
Per your comment, if you want to do an update, you'll need to include the parameter(s) that identify the rows to update. If this is a single row, use the primary key value:
command.CommandText = "update URL_Entries set UrlColumn = #url, ModifiedDate = #now where ID = #id";
You're using an INSERT function, that is 'ADD NEW RECORDS'
If you want an update, you'll want an UPDATE function
UPDATE tablename
SET column1 = 'x', column2 = 'y'
WHERE id = z

How to use UPDATE in ado net

I need to perform an update in a table(Homework). But it is not just replacing an old value with a new one; to the already existing value in the column i have to add(SUM) the new value(the column is of type int).
This is what i did so far but i am stuck:
protected void subscribeButton_Click(object sender, EventArgs e)
{
string txtStudent = (selectedStudentLabel.Text.Split(' '))[0];
int studentIndex = 0;
studentIndex = Convert.ToInt32(txtStudent.Trim());
SqlConnection conn = new SqlConnection("Server=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Trusted_Connection=True;User Instance=yes");
conn.Open();
string sql2 = "UPDATE student SET moneyspent = " + ?????? + " WHERE id=" + studentIndex + ";";
SqlCommand myCommand2 = new SqlCommand(sql2, conn);
try
{
conn.Open();
myCommand2.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex);
}
finally
{
conn.Close();
}
}
What should i add intead of ??? to achieve my goal?
Is it possible to do it this way? I want to avoid using to many queries.
If i understand you correctly (i'm not sure i do) you want something like this:
string sql2 = "UPDATE student SET moneyspent = moneyspent + #spent WHERE id=#id";
SqlCommand myCommand2 = new SqlCommand(sql2, conn);
myCommand2.Parameters.AddWithValue("#spent", 50 )
myCommand2.Parameters.AddWithValue("#id", 1 )
Notice how i've used parameters and not string concatenation, very important!!

Categories

Resources