update database by decrement stock C# and mysql - c#

I have two drop down lists that effect each over, for example if you choose UK in the first drop down the second drop down will be populated from the UK table, if you select Germany it will be populated via German table and so on. each table contains the same three columns Specie, Specie_Price and Stock. I would like to reduce the stock integer by 1 each time a specie is chose from the second list and a button click happens. I am lost on how to build a update statement to do this on the selection from the second drop down, I would appriciate any help at all. I will post code bellow to give you better understanding on what I mean.
code for first drop down list on page load (country selection)
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
MySqlCommand cd2 = new MySqlCommand("SELECT * FROM Country", cs);
cs.Open();
MySqlDataReader ddlCountry = cd2.ExecuteReader();
ddlcountry.DataSource = ddlCountry;
ddlcountry.DataValueField = "Country";
ddlcountry.DataTextField = "Country";
ddlcountry.DataBind();
cs.Close();
cs.Dispose();
}
}
Code that populates the drop down with the Specie from the country chosen
protected void ddlcountry_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlcountry.Text != string.Empty)
{
MySqlCommand cd = new MySqlCommand(string.Format("SELECT * FROM {0}_Animals",
ddlcountry.Text), cs);
cs.Open();
MySqlDataReader ddlSpecie = cd.ExecuteReader();
DdPetPist.DataSource = ddlSpecie;
DdPetPist.DataValueField = "Specie";
DdPetPist.DataTextField = "Specie";
DdPetPist.DataBind();
cs.Close();
cs.Dispose();
}
}
so the what I want is that when they have chose there country then the specie they click button and id decrements the Stock of the table chosen buy 1.
I hope some one can help, thank you.
!!UPDATE ANSWER!!
Got it working 100% in the end,
protected void Button3_Click(object sender, EventArgs e)
{
string selection_price = DdPetPist.SelectedValue;
var myquery = string.Format("UPDATE Animals SET Stock = Stock - 1 WHERE Specie ='{1}' and Country ='{0}'", ddlcountry.SelectedItem.ToString().Trim(), selection_price);
using (MySqlConnection c = new MySqlConnection(connection string here))
using (MySqlCommand cmd = new MySqlCommand(myquery, c))
{
c.Open();
cmd.ExecuteNonQuery();
c.Close();
}
}

First, hook up a button click event handler, and then in the handler do something like this:
var sql = string.Format(
"UPDATE {0}_Animals SET Stock = Stock - 1 WHERE Specie = #Specie",
ddlcountry.Text);
using (MySqlConnection c = new MySqlConnection(cString))
using (MySqlCommand cmd = new MySqlCommand(sql, c))
{
c.Open();
cmd.Parameters.AddWithValue("#Specie", specie);
cmd.ExecuteNonQuery();
}
where cString is the connection string and specie is the identifier. I'm not 100% sure where that comes from, but I think the drop down lists selected value.

Related

Invalid columns names Insert statement

I am trying to create add button in the gridview. I have 3 joining tables and 3 drop-down lists.
That is the error that I get:
Additional information: Invalid column name 'Quotation_Number'. Invalid column name 'Customer_Name'. Invalid column name 'Machine_Model'.
Can you help me? I think the problem is in the insert statement
Thanks
public void userSales()
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT SalesActivity.Activity_ID, SalesActivity.Date, SalesActivity.Quatation_Number, CUSTOMER.Customer_Name, PRODUCTS.Machine_Model, SalesActivity.Quantity, SalesActivity.valueGBR, SalesActivity.valueEUR, SalesActivity.Rate, SalesActivity.weightedValue, STATUS.Status, SalesActivity.estDecisionDate, SalesActivity.PromisedDeliveryDate FROM SalesActivity INNER JOIN CUSTOMER ON SalesActivity.Customer_ID = CUSTOMER.Customer_ID INNER JOIN PRODUCTS ON SalesActivity.Product_ID = PRODUCTS.Product_ID INNER JOIN STATUS ON SalesActivity.Status_ID = STATUS.Status_ID ", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow()); // if record not found then returning a blank table structure
GridView1.DataSource = ds;
GridView1.DataBind();
int columncount = GridView1.Rows[0].Cells.Count;
GridView1.Rows[0].Cells.Clear();
GridView1.Rows[0].Cells.Add(new TableCell());
GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
GridView1.Rows[0].Cells[0].Text = "No Records Found";
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex; //this open new index that is edit mode
userSales();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1; //after cancel button want go to one index back that's y -1
userSales();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AddNew"))
{
TextBox txtActivity = (TextBox)GridView1.FooterRow.FindControl("ftxtActivity");
TextBox ftxtDate = (TextBox)GridView1.FooterRow.FindControl("ftxtDate");
TextBox ftxtQno = (TextBox)GridView1.FooterRow.FindControl("ftxtQno");
DropDownList fddlCName = GridView1.FooterRow.FindControl("fddlCName") as DropDownList;
DropDownList fddlMmodel = GridView1.FooterRow.FindControl("fddlMmodel") as DropDownList;
TextBox ftxtQuantity = (TextBox)GridView1.FooterRow.FindControl("ftxtQuantity");
TextBox ftxtvalueGBR = (TextBox)GridView1.FooterRow.FindControl("ftxtvalueGBR");
TextBox ftxtvalueEUR = (TextBox)GridView1.FooterRow.FindControl("ftxtvalueEUR");
TextBox ftxtRate = (TextBox)GridView1.FooterRow.FindControl("ftxtRate");
TextBox ftxtweightedValue = (TextBox)GridView1.FooterRow.FindControl("ftxtweightedValue");
DropDownList fddlStatus = GridView1.FooterRow.FindControl("fddlStatus") as DropDownList;
TextBox ftxtestDecisionDate = (TextBox)GridView1.FooterRow.FindControl("ftxtestDecisionDate");
TextBox ftxtPromisedDeliveryDate = (TextBox)GridView1.FooterRow.FindControl("ftxtPromisedDeliveryDate");
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO SalesActivity(Activity_ID, Date, Quotation_Number, Customer_Name, Machine_Model,Quantity, valueGBR, valueEUR, Rate, weightedValue, Status, estDecisionDate, PromisedDeliveryDate) VALUES(#Activity_ID, #Date, #Quotation_Number, #Customer_Name, #Machine_Model, #Quantity, #valueGBR, #valueEUR, #Rate, #weightedValue, #Status, #estDecisionDate, #PromisedDeliveryDate)", con);
cmd.Parameters.AddWithValue("#Activity_ID", txtActivity.Text.Trim());
cmd.Parameters.AddWithValue("#Date", ftxtDate.Text.Trim());
cmd.Parameters.AddWithValue("#Quotation_Number", ftxtQno.Text.Trim());
cmd.Parameters.AddWithValue("#Customer_Name", fddlCName.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Machine_Model", fddlMmodel.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Quantity", ftxtQuantity.Text.Trim());
cmd.Parameters.AddWithValue("#valueGBR", ftxtvalueGBR.Text.Trim());
cmd.Parameters.AddWithValue("#valueEUR", ftxtvalueEUR.Text.Trim());
cmd.Parameters.AddWithValue("#weightedValue",ftxtweightedValue.Text.Trim());
cmd.Parameters.AddWithValue("#Rate", ftxtRate.Text.Trim());
cmd.Parameters.AddWithValue("#Status", fddlStatus.SelectedItem.Text);
cmd.Parameters.AddWithValue("#estDecisionDate", ftxtestDecisionDate.Text.Trim());
cmd.Parameters.AddWithValue("#PromisedDeliveryDate", ftxtPromisedDeliveryDate.Text.Trim());
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
userSales();
Response.Write("<script language=javascript>alert('" + txtActivity.Text + "'+'Sale Details inserted successfully');</script>");
}
else
{
Response.Write("<script language=javascript>alert('" + txtActivity.Text + "'+' Sale Details not inserted');</script>");
}
}
}
Your Select Statement is executing this...
SELECT SalesActivity.Activity_ID
,SalesActivity.DATE
,SalesActivity.Quatation_Number
,CUSTOMER.Customer_Name
,PRODUCTS.Machine_Model
,SalesActivity.Quantity
,SalesActivity.valueGBR
,SalesActivity.valueEUR
,SalesActivity.Rate
,SalesActivity.weightedValue
,STATUS.STATUS
,SalesActivity.estDecisionDate
,SalesActivity.PromisedDeliveryDate
FROM SalesActivity
INNER JOIN CUSTOMER ON SalesActivity.Customer_ID = CUSTOMER.Customer_ID
INNER JOIN PRODUCTS ON SalesActivity.Product_ID = PRODUCTS.Product_ID
INNER JOIN STATUS ON SalesActivity.Status_ID = STATUS.Status_ID
Machine_Model and Customer_Name do not belong to SalesActivity Table, they belong to Products and Customer respectively. And your issue with Quotation_Number is Quatation_Number in the select.
change this...
SqlCommand cmd = new SqlCommand("INSERT INTO SalesActivity(Activity_ID, Date, Quotation_Number, Customer_Name, Machine_Model,Quantity, valueGBR, valueEUR, Rate, weightedValue, Status, estDecisionDate, PromisedDeliveryDate) VALUES(#Activity_ID, #Date, #Quotation_Number, #Customer_Name, #Machine_Model, #Quantity, #valueGBR, #valueEUR, #Rate, #weightedValue, #Status, #estDecisionDate, #PromisedDeliveryDate)", con);
to this...
SqlCommand cmd = new SqlCommand("INSERT INTO SalesActivity(Activity_ID, Date, Quatation_Number,Quantity, valueGBR, valueEUR, Rate, weightedValue, estDecisionDate, PromisedDeliveryDate) VALUES(#Activity_ID, #Date, #Quotation_Number, #Quantity, #valueGBR, #valueEUR, #Rate, #weightedValue, #estDecisionDate, #PromisedDeliveryDate)", con);
and remove the following lines...
cmd.Parameters.AddWithValue("#Customer_Name", fddlCName.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Machine_Model", fddlMmodel.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Status", fddlStatus.SelectedItem.Text);
The insert should now work.

C# Displaying a sql database object's name in a label.Text property on "SelectedIndexChanged" Event

I am trying to make a small contact book that takes contacts details from a mssql database.It has 3 tables: contacts, last_talk(last time i talked with a contact+short description of the discussion), and another table(that has both primary keys from the first 2 tables )
On the form(tab of tabcontrol) where i display the contacts, i have added 2 listboxes, one loads and displays the contacts names, and the second listbox loads the "Last talk" list for every contact i select depending how many "talks" i had with a contact.
What i am trying to do now is: when i select a contact, i also want to display near the listboxes, some labels for the contact name, company, etc, that change their text to the database entry for the selected contact's name/company...
Here is a part of the code:
private void lstContactList_SelectedIndexChanged(object sender, EventArgs e)
{
PopulateTalkList();
PopulateContactLabels();
}
private void ContactBookForm_Load(object sender, EventArgs e)
{
PopulateContactList();
}
private void PopulateContactList()
{
string query = "SELECT * FROM Contact";
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter(query, connection))
{
connection.Open();
DataTable contactTable = new DataTable();
adapter.Fill(contactTable);
lstContactList.DisplayMember = "Name";
lstContactList.ValueMember = "Id";
lstContactList.DataSource = contactTable;
}
}
here is the method that i try to use to change the labels:
private void PopulateContactLabels()
{
string query = "SELECT * FROM Contact";
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
connection.Open();
SqlDataReader rdr = command.ExecuteReader();
while (rdr.Read())
{
lblContactName.Text = rdr["Name"].ToString();
lblCompany.Text = rdr["Company"].ToString();
lblOccupation.Text = rdr["Occupation"].ToString();
lblPhoneNumber.Text = rdr["PhoneNumber"].ToString();
lblEmail.Text = rdr["Email"].ToString();
}
rdr.Close();
connection.Close();
}
}
And it does change the labels, but it selects the last contact added to the database, and it doesn't change when i select another contact.
What am i doing wrong?
That's because in your PopulateContactLabels method, you are selecting the whole Contact table and then reading through the whole list, so it's always the last one which is shown.
You need a query more like SELECT * FROM Contact WHERE ContactId = #contactID, and then add the contactId (or whatever value you are using to find the contact) as a parameter on the SqlCommand object.

How to AutoFill second TextBox according to first TextBox with the corresponding data in the DataBase

In my winform, there's a datatable with 2 column, 1st one is studentname & 2nd column is StudentAverage.
First txtbx is autosuggest(studentname).
How to make the second txtbx automaticaly fill according to 1st txtbx (2nd txtbx fill with the corresponding record of second column (studentsavrage)?
this is for the 1st txtbx; shows StudentNames
private void txtbxName_TextChanged(object sender, EventArgs e)
{
AutoCompleteStringCollection namesCollection = new AutoCompleteStringCollection();
string StrCmd = "SELECT * FROM School";
string ConnStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\School_Database.accdb";
OleDbConnection MyConn = new OleDbConnection(ConnStr);
MyConn.Open();
OleDbCommand Cmd = new OleDbCommand(StrCmd, MyConn); ;
OleDbDataReader ObjReader = Cmd.ExecuteReader();
if (ObjReader != null)
{
while (ObjReader.Read())
namesCollection.Add(ObjReader["StudentName"].ToString());
}
else
{
MessageBox.Show("Data not found");
}
ObjReader.Close();
MyConn.Close();
txtbxName.AutoCompleteMode = AutoCompleteMode.Suggest;
txtbxName.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtbxName.AutoCompleteCustomSource = namesCollection;
}
I assume you are developing with WinForms.
First out: since a where clause is missing from your query you are not filtering while user inputs text. You should move AutoCompleteStrinCollection fetching in another place if you don't want that.
Your problem: the simplier way here is to manually update the second textbox in your txtbxName_TextChanged method.
private void txtbxName_TextChanged(object sender, EventArgs e)
{
string StrCmd = String.Format( "SELECT AGE FROM School WHERE name '{0', txtbox1.Text");
//perform query as you already do and read result
textbox2.Text = cmd.ExecuteScalar()
}
P.S: in real world things are not done the way you are doing under many many aspects

reducing stock by one on selection

I am trying to select film by using on select command, print the title in a label once selected.. that works well.
next part is the selected film will then decrement 1 from the database stock on button click. This is where I think I am getting confused, its showing no errors until the button click takes place.
C# code for update query
protected void Button2_Click(object sender, EventArgs e)
{
var myquery = string.Format("UPDATE DVD SET Stock = Stock - 1");
da.InsertCommand = new OleDbCommand("INSERT INTO DVD (Stock) VALUES (#MessageLabel)", conn);
{
da.InsertCommand.Parameters.AddWithValue("#Stock", MessageLabel.Text);
conn.Open();
da.InsertCommand.ExecuteNonQuery();
using (OleDbCommand cmd = new OleDbCommand(myquery, conn))
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
}
}
Previous code for select event
public void Latest_DVD()
{
{
using (OleDbDataAdapter dataquer = new OleDbDataAdapter("SELECT Title,Category,Director,Stock,Year FROM DVD ", conn))
{
dataquer.Fill(dt);
}
}
DG_Latest.ShowHeader = true;
DG_Latest.DataSource = dt;
DG_Latest.DataBind();
conn.Close();
conn.Dispose();
}
protected void Latest_DVD_SelectedIndexChanged(Object sender, EventArgs e)
{
GridViewRow row = DG_Latest.SelectedRow;
MessageLabel.Text = "You selected to rent " + row.Cells[1].Text + ".";
}
so I am thinking I have the query wrong and possibly nor retrieve the update from the label but maybe the on select its self... I am not sure through.
the error it is showing is
Data type mismatch in criteria expression.
just after the connection is open
As #afzalulh said, remove the insert part. And change myquery string to be:
var myquery = string.Format("UPDATE DVD SET Stock = Stock - 1 WHERE Title = #Title");
var row = DB_Latest.SelectedRow;
var title = row.Cells[0].Text;
var cmd = new OleDbCommand(myquery, conn);
cmd.Parameters.AddWithValue("#Title", title);
With that, you only update Stock for the selected DVD title only. Without adding WHERE clause, the query will decrease stock for all DVDs.
You want to update stock, there's no need to insert. I believe this is what you want:
protected void Button2_Click(object sender, EventArgs e)
{
var myquery = string.Format("UPDATE DVD SET Stock = Stock - 1");
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(myquery, conn))
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
}
EDIT: myquery should include WHERE as suggested by har07. Otherwise it will reduce all DVD's stock by 1.

Multiple drop down list change each overs Tables C# and MySql query

OK I have 2 Drop down list that effect each over when select, if user selects France from ddlcountry then DdPetPist is populated with France_Animals Table and when selects UK or Germany it populates with either the UK table or Germany table. this works well.
problem is I have a label print out displaying two things the price and stock pulled from UK_Animals table.
How can I alter my Table query to display the stock and price depending on the animal chosen at the moment if user selects dog it will show info but only for dogs in UK. I need it so this label changes with the country table.
The Two DropDown Lists
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
MySqlCommand cd2 = new MySqlCommand("SELECT * FROM Country", cs); // need to make it so changes database
cs.Open();
MySqlDataReader ddlCountry = cd2.ExecuteReader();
ddlcountry.DataSource = ddlCountry;
ddlcountry.DataValueField = "Country";
ddlcountry.DataTextField = "Country";
ddlcountry.DataBind();
cs.Close();
cs.Dispose();
MySqlCommand cd = new MySqlCommand("SELECT * FROM UK_Animals", cs);
cs.Open();
MySqlDataReader ddlSpecie = cd.ExecuteReader();
DdPetPist.DataSource = ddlSpecie;
DdPetPist.DataValueField = "Specie";
DdPetPist.DataTextField = "Specie";
DdPetPist.DataBind();
cs.Close();
cs.Dispose();
}
}
Code That Changes The Table When different Country Is Selected
protected void ddlcountry_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlcountry.Text != string.Empty)
{
MySqlCommand cd = new MySqlCommand(string.Format("SELECT * FROM {0}_Animals", ddlcountry.Text), cs);
cs.Open();
MySqlDataReader ddlSpecie = cd.ExecuteReader();
DdPetPist.DataSource = ddlSpecie;
DdPetPist.DataValueField = "Specie";
DdPetPist.DataTextField = "Specie";
DdPetPist.DataBind();
cs.Close();
cs.Dispose();
}
}
Code That Changes label Depending On Animal Selects (But Dose Not Change To Animal Table)
This Is What I cant get to Change to Cosponsoring Country Selection It remains Always In UK, I know why but do not Know How to Fix Its So It Changes With The Country Selection.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string selection_price = DdPetPist.SelectedValue;
string selection_stock = DdPetPist.SelectedValue;
string petPrice = string.Empty;
string available = string.Empty;
MySqlCommand cd_price = new MySqlCommand(String.Format("SELECT Specie_Price FROM UK_Animals WHERE Specie ='{0}'", selection_price), cs);
MySqlCommand cd_available = new MySqlCommand(String.Format("SELECT Stock FROM UK_Animals WHERE Specie ='{0}'", selection_stock), cs);
cs.Open();
petPrice = Convert.ToString(cd_price.ExecuteScalar());
available = Convert.ToString(cd_available.ExecuteScalar());
cs.Close();
PetPrice.Text = String.Format("Minimum Donation For A {0} Is £{1}.", selection_price, petPrice);
Availble.Text = String.Format("{0}'s Avalible {1}.", selection_stock, available);
}
Please is there a way to do this and if so how?
Thank You.
Both queries in DropDownList1_SelectedIndexChanged point to UK_Animals and thus the selection of the table of a different country you do in ddlcountry_SelectedIndexChanged does not have any effect when writing to the labels.
As far as DdPetPist.DataSource is updated with the right country information, you should access this variable from DropDownList1_SelectedIndexChanged, instead of connecting to the DB again. Alternatively, you might keep the connection to the DB by selecting the table of the corresponding country; but this option does not sound too right: it would involve not-completely-necessary DB connections and global variables.
UPDATE
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string selection_price = DdPetPist.SelectedValue;
string selection_stock = DdPetPist.SelectedValue;
string petPrice = string.Empty;
string available = string.Empty;
MySqlCommand cd_price = new MySqlCommand(String.Format("SELECT Specie_Price FROM {0}_Animals WHERE Specie ='{1}'", ddlcountry.Text, selection_price), cs);
MySqlCommand cd_available = new MySqlCommand(String.Format("SELECT Stock FROM {0}_Animals WHERE Specie ='{1}'", ddlcountry.Text, selection_stock), cs);
cs.Open();
petPrice = Convert.ToString(cd_price.ExecuteScalar());
available = Convert.ToString(cd_available.ExecuteScalar());
cs.Close();
PetPrice.Text = String.Format("Minimum Donation For A {0} Is £{1}.", selection_price, petPrice);
Availble.Text = String.Format("{0}'s Avalible {1}.", selection_stock, available);
}
This is the "option 2"; the best option is adapting these queries to read from the local copy of the table of the given country, stored in DdPetPist.DataSource.

Categories