Update count of an item stored in a database - c#

I'm setting up a point of sales system with counts of products in stock. Unfortunately, I can't seem to get my method to update the quantities of one of my products.
I can execute the query in the command line with a value and it will update the count of the product. The count is stored in the text property of txtBanCount here.
namespace POSSystem
{
public partial class POSsystem : Form
{
public POSsystem()
{
InitializeComponent();
}
MySqlConnection conn;
private void MySqlConnect()
{
string connStr = "server=localhost;user=root;database=possystem;port=3306;password=bhuytr83";
conn = new MySqlConnection(connStr);
try
{
conn.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
throw;
}
}
private void UpdateQuantities()
{
string banSqlUpdate = "Update Products SET count = '" + txtBanCount + "' + WHERE prodName = 'Bananas';";
MySqlCommand cmdBanUpdate = new MySqlCommand(banSqlUpdate,conn);
cmdBanUpdate.ExecuteNonQuery();
}
I expect the 'Count' column of my Products table to be set to the text displayed on txtBanCount.

I assume that txtBanCount is a text control right, so use it's Text
property txtBanCount.Text
so please use below code
private void UpdateQuantities()
{
string banSqlUpdate = "Update Products SET count = '" + txtBanCount.Text + "' WHERE prodName = 'Bananas';";
MySqlCommand cmdBanUpdate = new MySqlCommand(banSqlUpdate,conn);
cmdBanUpdate.ExecuteNonQuery();
}

Related

Multiple ReadData in a Menu ComboBox (MySQL/C#)

I was trying to show the values of my data in my different tables in these combo boxes which I made. I tried making multiple read data but it's impossible without getting an error. Is there other way to show these values in these different combo boxes?
Menu Here
private void VoteMenu_Load(object sender, EventArgs e)
{
displayCandidate();
}
public void displayCandidate()
{
//Connection
String connection = "server=localhost;user id=root;password=root;persistsecurityinfo=True;database=votingdb;";
//Inserting Data
String displayPresident = "SELECT * FROM president";
String displayVicePresident = "SELECT * FROM vicepresident";
String displaySecretary = "SELECT * FROM secretary";
String displayTreasurer = "SELECT * FROM treasurer";
String displayAuditor = "SELECT * FROM auditor";
String displayPro = "SELECT * FROM pro";
MySqlDataReader dataReader;
//Connection and Inserting of Data
using (MySqlConnection con = new MySqlConnection(connection))
{
//Opening of Connection
con.Open();
//FOR PRESIDENT
using (MySqlCommand votePresident = new MySqlCommand(displayPresident, con))
{
try
{
int votePres = 0;
votePres = votePresident.ExecuteNonQuery();
dataReader = votePresident.ExecuteReader();
//Loop to read the Data
while (dataReader.Read())
{
String rollPresf = dataReader.GetString("firstName");
String rollPresl = dataReader.GetString("lastName");
presidentbox.Items.Add(rollPresf + " " + rollPresl);
}
}
catch (Exception ex)
{
MessageBox.Show("Failed to Vote" + ex);
}
}
//FOR VICE PRESIDENT
using (MySqlCommand voteVicePresident = new MySqlCommand(displayVicePresident, con))
{
try
{
int voteVpres = 0;
voteVpres = voteVicePresident.ExecuteNonQuery();
dataReader = voteVicePresident.ExecuteReader();
}
catch (Exception ex)
{
MessageBox.Show("Failed to Vote" + ex);
}
}
There are more position to be filled, and I also tried making every position to show their values inside my database which has different tables like this
Database

Databinding not updating database until after move to previous or next record

Creating a project for school, I have a form with some user controls.
3 textboxes a checkbox and 2 buttons for navigating through the records.
When I change the text on one of the textboxes, the data will only reflect to the database when I click the "Next" or "Prev" button.
public partial class Navigeren : UserControl
{
private readonly SqLiteDataAccess _sqLiteDataAccess;
private Timer _saveTimer;
private DataViewManager _dsView;
public Navigeren()
{
InitializeComponent();
_sqLiteDataAccess = new SqLiteDataAccess();
DataBinding();
_saveTimer = new Timer {Interval = 1000};
_saveTimer.Tick += _saveTimer_Tick;
_saveTimer.Start();
}
private void _saveTimer_Tick(object sender, EventArgs e)
{
_sqLiteDataAccess.UpdatePersonen(_dsView.DataSet);
// Tried using SqLiteDataAccess.PersonenDataSet gives me the same result.
}
private void DataBinding()
{
_dsView = SqLiteDataAccess.PersonenDataSet.DefaultViewManager;
textId.DataBindings.Add("Text", _dsView, "Personen.id", false, DataSourceUpdateMode.OnPropertyChanged);
textNaam.DataBindings.Add("Text", _dsView, "Personen.name", false, DataSourceUpdateMode.OnPropertyChanged);
textAdres.DataBindings.Add("Text", _dsView, "Personen.adres", false, DataSourceUpdateMode.OnPropertyChanged);
checkGehuwd.DataBindings.Add("Checked", _dsView, "Personen.gehuwd", false, DataSourceUpdateMode.OnPropertyChanged);
}
private void buttonNext_Click(object sender, EventArgs e)
{
CurrencyManager cm = (CurrencyManager)this.BindingContext[_dsView, "Personen"];
if (cm.Position < cm.Count - 1)
{
cm.Position++;
}
}
private void buttonPrev_Click(object sender, EventArgs e)
{
if (this.BindingContext[_dsView, "Personen"].Position > 0)
{
this.BindingContext[_dsView, "Personen"].Position--;
}
}
}
Sorry for my english.
Greetings Andy
EDIT:
SQLiteDataAccess:
class SqLiteDataAccess
{
private SQLiteConnection _sqliteconnection;
private string _database = #"Database.sqlite";
private static DataSet _personenDataSet;
public static DataSet PersonenDataSet
{
get { return _personenDataSet; }
set { _personenDataSet = value; }
}
public SqLiteDataAccess()
{
OpenConnection();
CreateTable();
CreateTableGeslachten();
CreateTableLanden();
FillDataSet();
}
private void OpenConnection()
{
if (!File.Exists(_database))
SQLiteConnection.CreateFile(_database);
_sqliteconnection = new SQLiteConnection("Data Source=" + _database + ";Version=3;");
_sqliteconnection.Open();
}
private void CreateTable()
{
try
{
string sql = "CREATE TABLE Personen (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"name VARCHAR, " +
"adres VARCHAR, " +
"gehuwd INT, " +
"land INT, " +
"geslacht INT, " +
"telnr VARCHAR, " +
"studies VARCHAR, " +
"geboorteDatum DATETIME, " +
"foto BLOB)";
SQLiteCommand command = new SQLiteCommand(sql, _sqliteconnection);
command.ExecuteNonQuery();
}
catch (SQLiteException sle)
{
}
}
private void CreateTableGeslachten()
{
try
{
string sql = "CREATE TABLE Geslachten (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"geslacht TEXT," +
"FOREIGN KEY(id) REFERENCES Personen(geslacht));";
SQLiteCommand command = new SQLiteCommand(sql, _sqliteconnection);
command.ExecuteNonQuery();
InsertTableGeslachten();
}
catch (SQLiteException sle)
{
}
}
private void InsertTableGeslachten()
{
string sql = "INSERT INTO Geslachten(geslacht) VALUES('Man'), ('Vrouw');";
SQLiteCommand command = new SQLiteCommand(sql, _sqliteconnection);
command.ExecuteNonQuery();
}
private void CreateTableLanden()
{
try
{
string sql = "CREATE TABLE Landen (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"land TEXT," +
"FOREIGN KEY(id) REFERENCES Personen(land));";
SQLiteCommand command = new SQLiteCommand(sql, _sqliteconnection);
command.ExecuteNonQuery();
InsertTableLanden();
}
catch (SQLiteException sle)
{
}
}
public void Insert(string name, string adres, bool gehuwd, int land, int geslacht, string telnr, string studies,
string geboorteDatum, byte[] foto)
{
var sql =
new StringBuilder(
"insert into Personen (name, adres, gehuwd, land, geslacht, telnr, studies, geboorteDatum) values ('");
sql.Append(name).Append("','")
.Append(adres).Append("','")
.Append(Convert.ToInt32(gehuwd)).Append("','")
.Append(land).Append("','")
.Append(geslacht).Append("','")
.Append(telnr).Append("','")
.Append(studies).Append("','")
.Append(geboorteDatum).Append("');");
// .Append(foto).Append(");");
SQLiteCommand command = new SQLiteCommand(sql.ToString(), _sqliteconnection);
command.ExecuteNonQuery();
}
public void FillDataSet()
{
SqLiteDataAccess.PersonenDataSet = new DataSet();
try
{
string query = "select * from Personen";
SQLiteDataAdapter da = new SQLiteDataAdapter(query, _sqliteconnection);
da.Fill(PersonenDataSet, "Personen");
string query2 = "select id, geslacht from geslachten";
SQLiteDataAdapter da2 = new SQLiteDataAdapter(query2, _sqliteconnection);
da2.Fill(PersonenDataSet, "Geslachten");
string query3 = "select id, land from Landen";
SQLiteDataAdapter da3 = new SQLiteDataAdapter(query3, _sqliteconnection);
da3.Fill(PersonenDataSet, "Landen");
}
catch (Exception ex)
{
}
}
public void UpdatePersonen(DataSet ds)
{
try
{
string query = "select * from Personen";
SQLiteDataAdapter da = new SQLiteDataAdapter(query, _sqliteconnection);
SQLiteCommandBuilder sqLiteCommandBuilder = new SQLiteCommandBuilder(da);
da.Update(ds, "Personen");
}
catch (Exception ex)
{
MessageBox.Show("Test");
}
}
You don't need to change the position, you just need to call EndCurrentEdit method of the BindingManagerBase before save:
this.BindingContext[datasource, "datamember"].EndCurrentEdit();
Some Notes
Use BindingSource.
I recommend using a BindingSource component as data source which you want to use for data-binding. Then set the DataSource and DataMember of the BindingSource to the values which you want:
It enables you to perform data-binding at design time.
It enables you to use its methods and properties to navigation, add, remove and so on.
You can use it's sorting and filtering properties.
Use BindingNavigator.
Also use BindingNavigator control as a navigation toolbar. It's enough to set its BindingSource property to the BindingSource component which you used for data-binding, then its navigation button will do the job of navigation for you.
Also take a look at:
Why do I need to change the Binding Source Position before I can SaveChanges
Describes why changing position also does the trick.
Equivalent of MoveNext in VB.NET
Shows you how to create a rapid data application using designer features, data-binding, BindingSource and BindingNavigator using drag and drop. Also it share some useful links about these features.

How to insert data into two SQL Server tables in asp.net

I have two tables, the first table is Course and this table contains three columns Course_ID, Name_of_course, DeptID; and the second table is Department and it has three columns DeptID, DepName, College.
I put a GridView to display the data that I will add it. But when I write the command to insert the data in both tables the data don't add. I used this command
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
GridViewRow r = GridView1.SelectedRow;
Dbclass db = new Dbclass();
string s = "";
DataTable dt = db.getTable(s);
ddcollege.SelectedValue = dt.Rows[0]["College"].ToString();
dddept.SelectedValue = dt.Rows[1]["DepName"].ToString();
tbid.Text = r.Cells[0].Text;
tbcourse_name.Text = r.Cells[1].Text;
lblid.Text = tbid.Text;
lberr.Text = "";
}
catch (Exception ex)
{
lberr.Text = ex.Message;
}
}
protected void btadd_Click(object sender, EventArgs e)
{
try
{
if (tbid.Text == "")
{
lberr.Text = "Please input course id";
return;
}
if (tbcourse_name.Text == "")
{
lberr.Text = "Please input course name";
return;
}
string s = "Insert into Course(Course_ID,Name_of_course) values ('" + tbid.Text + "','" + tbcourse_name.Text + "')";
s = "INSERT INTO Department (DepName,College,DeptID) VALUES ('"+dddept.SelectedValue+"','"+ddcollege.SelectedValue+"','"+tbdeptID.Text+"')";
Dbclass db = new Dbclass();
if (db.Run(s))
{
lberr.Text = "The data is added";
lblid.Text = tbid.Text;
}
else
{
lberr.Text = "The data is not added";
}
SqlDataSource1.DataBind();
GridView1.DataBind();
}
catch (Exception ex)
{
lberr.Text = ex.Message;
}
}
Here is the Dbclass code:
public class Dbclass
{
SqlConnection dbconn = new SqlConnection();
public Dbclass()
{
try
{
dbconn.ConnectionString = #"Data Source=Fingerprint.mssql.somee.com;Initial Catalog=fingerprint;Persist Security Info=True;User ID=Fingerprint_SQLLogin_1;Password=********";
dbconn.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
//----- run insert, delete and update
public bool Run(String sql)
{
bool done= false;
try
{
SqlCommand cmd = new SqlCommand(sql,dbconn);
cmd.ExecuteNonQuery();
done= true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return done;
}
//----- run insert, delete and update
public DataTable getTable(String sql)
{
DataTable done = null;
try
{
SqlDataAdapter da = new SqlDataAdapter(sql, dbconn);
DataSet ds = new DataSet();
da.Fill(ds);
return ds.Tables[0];
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return done;
}
}
Thank you all
The main thing I can see is you are assigning two different things to your "s" variable.
At this point db.Run(s) the value is "Insert into Department etc" and you have lost the first sql string you assigned to "s"
Try:
string s = "Insert into Course(Course_ID,Name_of_course) values ('" + tbid.Text + "','" + tbcourse_name.Text + "')";
s += "INSERT INTO Department (DepName,College,DeptID) VALUES ('"+dddept.SelectedValue+"','"+ddcollege.SelectedValue+"','"+tbdeptID.Text+"')";
Notice the concatenation(+=). Otherwise as mentioned above using a stored procedure or entity framework would be a better approach. Also try to give your variables meaningful names. Instead of "s" use "insertIntoCourse" or something that describes what you are doing
When a value is inserted into a table(Table1) and and value has to be entered to into another table(Table2) on insertion of value to Table1, you can use triggers.
https://msdn.microsoft.com/en-IN/library/ms189799.aspx
"tbdeptID.Text" is giving you the department Id only right? You should be able to modify your first statement
string s = "Insert into Course(Course_ID,Name_of_course,) values ('" + tbid.Text + "','" + tbcourse_name.Text + "',)";
Please start running SQL Profiler, it is a good tool to see what is the actual query getting executed in server!

Passing same value of method to multiple forms

In my window application I have orderNumber that need to be passed to another form. This order number is generated by the code which I will put below. I am trying to pass only 1 identical order number to two locations but unfortunately, two different order number passed to both location. How can I make that only one order number is passed to both location.
Code that generates the order number:
public string orderNumber()
{
string ord = "ORD" + get_next_id() + DateTime.Now.Year;
return ord;
}
public int get_next_id()
{
OleDbConnection objConnection = null;
OleDbCommand objCmd = null;
String sql;
int res;
// Create and open the connection object
objConnection = new OleDbConnection(connString);
objConnection.Open();
sql = "SELECT IIF(MAX(Customer.NumGenerate) IS NULL,100,MAX(Customer.NumGenerate)) as v_max FROM Customer;";
objCmd = new OleDbCommand(sql, objConnection);
res = (int)objCmd.ExecuteScalar();
++res;
objConnection.Close();
return res;
}
In the first form the following insert method uses the order number:
private void SaveAllListItems()
{
string listItems = string.Empty;
foreach (var listBoxItem in listBox1.Items)
{
listItems += listBoxItem.ToString();
if (listBox1.Items.IndexOf(listBoxItem) < listBox1.Items.Count - 1)
{
listItems += ", ";
}
}
InsertUser(maskedTextBox1.Text, comboBox1.Text, maskedTextBox2.Text, maskedTextBox3.Text, maskedTextBox4.Text, maskedTextBox5.Text,
maskedTextBox6.Text, maskedTextBox7.Text, maskedTextBox8.Text, maskedTextBox9.Text, listItems, DateTime.Now, maskedTextBox10.Text, orderNumber(), get_next_id());
;
}
In second form I want to use the same order number which is being used to insert user. right now I have the following code which is not working as form1 has different order number and form 2 has different.
private void FindOrder()
{
Form1 m = new Form1();
string number = m.orderNumber();
// string number = "ORD1012013";
string InvSql = "SELECT (Customer.[Title] + SPACE(2) + Customer.[Customer's Name]) as CustomerName, Customer.[Customer's Ebayname], Customer.[Email Address], Customer.[Phone Number], (Customer.[Address 1] + SPACE(2) +Customer.[Address 2] + SPACE(2) + Customer.[City] + SPACE(2) + Customer.[Post Code]+ SPACE(2) + Customer.[Country]) as Address, Customer.[Item Purchased], Customer.[Purchased Date], Customer.[Total Price], Customer.[OrderNumber] FROM Customer WHERE Customer.[OrderNumber]= '" + number + "'";
OleDbConnection cnn = new OleDbConnection(connString);
OleDbCommand cmdOrder = new OleDbCommand(InvSql, cnn);
cnn.Open();
OleDbDataReader rdrOrder = cmdOrder.ExecuteReader();
rdrOrder.Read();
custName.Text = rdrOrder["CustomerName"].ToString();
ebayName.Text = rdrOrder["Customer's Ebayname"].ToString();
email.Text = rdrOrder["Email Address"].ToString();
phone.Text = rdrOrder["Phone Number"].ToString();
address.Text = rdrOrder["Address"].ToString();
item.Text = rdrOrder["Item Purchased"].ToString();
date.Text = Convert.ToString(Convert.ToDateTime(rdrOrder["Purchased Date"]));
price.Text = rdrOrder["Total Price"].ToString();
order.Text = rdrOrder["OrderNumber"].ToString();
rdrOrder.Close();
cnn.Close();
}
How can I pass same order number to both location?
Data can be passed between forms in different ways.
Here's a good tutorial on how to do that.The Constructor and Property approach is easier to implement.
You dont seem to be saving the orderid on the form1 class
Declare a variable for the OrderID on Form1 class
string OrderId;
Modify your exisiting Method
public string orderNumber()
{
OrderId = "ORD" + OrderId + DateTime.Now.Year;
}
And then follow the Constructor Approach to pass over the value to PrintForm
Again declare a variable for orderID inside the PrintForm class
string OrderId;
Change your PrintForm Constructor to this
public PrintForm(string value)
{
InitializeComponent();
OrderId=value;
}
on Form1 Button click event
private void button1_Click(object sender, System.EventArgs e)
{
PrintForm frm=new PrintForm(OrderId);
PrintForm.Show();
}
Create a container class with a static property in the same namespace:
class clsDummy
{
internal static string ptyValue { get; set; }
}
you can assign this property where you are getting order id:
public string orderNumber()
{
string ord = "ORD" + get_next_id() + DateTime.Now.Year;
clsDummy.ptyValue =ord ;
return ord;
}
after that where ever you want to access just check value inside : clsDummy.ptyValue

SQL Syntax Error (INSERT command)

I have a form with a text box and button, such that when the user clicks the button, the specified name in the text box is added to a table in my sql database. The code for the button is as follows:
private void btnAddDiaryItem_Click(object sender, EventArgs e)
{
try
{
string strNewDiaryItem = txtAddDiaryItem.Text;
if (strNewDiaryItem.Length == 0)
{
MessageBox.Show("You have not specified the name of a new Diary Item");
return;
}
string sqlText = "INSERT INTO tblDiaryTypes (DiaryType) VALUES = ('" + strNewDiaryItem + "');";
cSqlQuery cS = new cSqlQuery(sqlText, "non query");
PopulateInitialDiaryItems();
MessageBox.Show("New Diary Item added succesfully");
}
catch (Exception ex)
{
MessageBox.Show("Unhandled Error: " + ex.Message);
}
}
The class cSqlQuery is a simple class that executes various T-SQL actions for me and its code is as follows:
class cSqlQuery
{
public string cSqlStat;
public DataTable cQueryResults;
public int cScalarResult;
public cSqlQuery()
{
this.cSqlStat = "empty";
}
public cSqlQuery(string paramSqlStat, string paramMode)
{
this.cSqlStat = paramSqlStat;
string strConnection = BuildConnectionString();
SqlConnection linkToDB = new SqlConnection(strConnection);
if (paramMode == "non query")
{
linkToDB.Open();
SqlCommand sqlCom = new SqlCommand(paramSqlStat, linkToDB);
sqlCom.ExecuteNonQuery();
linkToDB.Close();
}
if (paramMode == "table")
{
using (linkToDB)
using (var adapter = new SqlDataAdapter(cSqlStat, linkToDB))
{
DataTable table = new DataTable();
adapter.Fill(table);
this.cQueryResults = table;
}
}
if (paramMode == "scalar")
{
linkToDB.Open();
SqlCommand sqlCom = new SqlCommand(paramSqlStat, linkToDB);
this.cScalarResult = (Int32)sqlCom.ExecuteScalar();
linkToDB.Close();
}
}
public cSqlQuery(SqlCommand paramSqlCom, string paramMode)
{
string strConnection = BuildConnectionString();
SqlConnection linkToDB = new SqlConnection(strConnection);
paramSqlCom.Connection = linkToDB;
if (paramMode == "table")
{
using (linkToDB)
using (var adapter = new SqlDataAdapter(paramSqlCom))
{
DataTable table = new DataTable();
adapter.Fill(table);
this.cQueryResults = table;
}
}
if (paramMode == "scalar")
{
linkToDB.Open();
paramSqlCom.Connection = linkToDB;
this.cScalarResult = (Int32)paramSqlCom.ExecuteScalar();
linkToDB.Close();
}
}
public string BuildConnectionString()
{
cConnectionString cCS = new cConnectionString();
return cCS.strConnect;
}
}
The class works well throughout my application so I don't think the error is in the class, but then I can't be sure.
When I click the button I get the following error message:
Incorrect syntax near =
Which is really annoying me, because when I run the exact same command in SQL Management Studio it works fine.
I'm sure I'm missing something rather simple, but after reading my code through many times, I'm struggling to see where I have gone wrong.
you have to remove = after values.
string sqlText = "INSERT INTO tblDiaryTypes (DiaryType) VALUES ('" + strNewDiaryItem + "');"
and try to use Parameterized queries to avoid Sql injection. use your code like this. Sql Parameters
string sqlText = "INSERT INTO tblDiaryTypes (DiaryType) VALUES (#DairyItem);"
YourCOmmandObj.Parameters.AddwithValue("#DairyItem",strNewDiaryIItem)
Remove the = after VALUES.
You do not need the =
A valid insert would look like
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
Source: http://www.w3schools.com/sql/sql_insert.asp
Please use following:
insert into <table name> Values (value);
Remove "=", and also i would recommend you to use string.format() instead of string concatenation.
sqlText = string.format(INSERT INTO tblDiaryTypes (DiaryType) VALUES ('{0}'), strNewDiaryItem);"

Categories