How to save value for foreign keys? - c#

I want save the ID of the selected subjectname in a DataGridView and also the ID of the student whose year level is selected in the combobox. So my reference for getting the student and subject is the school year and the year level. I want to save it in my table Schedule which has Registration_registrationID (FK), Student_studentID (FK), yearlevel and schoolyear:
Here's my code :
private void btn_add_Click(object sender, EventArgs e)
{
string reg = "";
string schoolyear = txt_startYr.Text + "-" + txt_endYr.Text;
MySqlConnection conn, conn1, conn2;
MySqlCommand cmd2;
MySqlDataReader reader, reader1;
List<DataGridViewRow> selectedRows = (from row in dg_subjects.Rows.Cast<DataGridViewRow>() where Convert.ToBoolean(row.Cells[3].Value) == true select row).ToList();
if (selectedRows.Count >= 1)
{
if (MessageBox.Show(string.Format("Are you sure you want to add this subject?", selectedRows.Count), "Confirmation", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
foreach (DataGridViewRow row in selectedRows)
{
try
{
conn = new MySqlConnection(myconn);
conn.Open();
string subject = "Select subjectID from southpoint_school.subject WHERE subject_name = '" + row.Cells[0].Value.ToString() + "';";
MySqlCommand cmd = new MySqlCommand(subject, conn);
reader = cmd.ExecuteReader();
reader.Read();
string subj = reader.GetString("subjectID");
conn.Close();
conn1 = new MySqlConnection(myconn);
conn1.Open();
string query = "Select regID from southpoint_school.registration where yearLevel = '" + cmb_year.Text + "' AND schoolYear = '" + schoolyear + "';";
MySqlCommand cmd1 = new MySqlCommand(query, conn1);
reader1 = cmd1.ExecuteReader();
while (reader1.Read())
{
conn2 = new MySqlConnection(myconn);
reg = reader1.GetString("regID");
string query1 = "INSERT INTO southpoint_school.schedule (Registration_regID, Subject_subjectID, yearLevel, school_year) values ('" + reg + "','" + subj + "','" + cmb_year.Text + "','" + schoolyear + "')";
cmd2 = new MySqlCommand(query1, conn2);
conn2.Open();
cmd2.ExecuteNonQuery();
MessageBox.Show("Successfully Saved");
conn2.Close();
}
conn1.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
else
{
MessageBox.Show("Please select a Subject");
}
}
It doesn't give an error but it does nothing.

Related

Is there equivalent C# function for "mysqli_fetch_array"?

So I want to manually convert the PHP function to C# Windows Form but I don't know the equivalent function mysqli_fetch_array in C# and how to do array PHP in C#?
I've googling but there is no correct solution.
This is in C# Windows Form
openConnection();
string selectQuery = "SELECT * FROM data_pegawai WHERE is_deleted=0 AND username='" + user + "'";
MySqlCommand command = new MySqlCommand(selectQuery, conn);
MySqlDataReader reader = command.ExecuteReader();
while (valuesList = reader.Read())
{
id = reader.GetInt32("id_peg");
}
closeConnection();
kembali = bayar - subtotal;
lblKembali.Text = kembali.ToString();
string insertQuery1 = "UPDATE data_transaksi SET status_pengerjaan='Lunas',potongan_harga='" + diskonrupiah.ToString() + "',subtotal='" + txtSubtotal.Text + "' WHERE id_transaksi =" + int.Parse(txtID_T.Text);
string insertQuery2 = "INSERT INTO pegawai_onduty VALUES(NULL, '" + id + "','" + txtID_T.Text + "')";
openConnection();
string selectQuery1 = "SELECT dsp.id_spareparts, dtsp.JUMLAH_SPAREPART from data_transaksi dt LEFT JOIN detail_transaksi_sparepart dtsp ON dt.id_transaksi=dtsp.id_transaksi LEFT JOIN spareparts_motor sm ON dtsp.ID_SPAREPARTMOTOR=sm.ID_SPAREPARTMOTOR LEFT JOIN data_spareparts dsp ON sm.id_spareparts=dsp.id_spareparts where dtsp.id_transaksi =" + int.Parse(txtID_T.Text);
MySqlCommand command1 = new MySqlCommand(selectQuery1, conn);
MySqlDataReader reader1 = command1.ExecuteReader();
while (reader1.Read())
{
int getData = "SELECT jumlah_stok FROM data_spareparts dsp WHERE id_spareparts='$jml[0]'";
}
closeConnection();
runQuery(insertQuery1);
runQuery(insertQuery2);
loadTransaksi();
And this is PHP code that I trying to convert to
while($jml=mysqli_fetch_array($dataJumlah))
{
$getData = mysqli_query($conn, "SELECT jumlah_stok FROM data_spareparts dsp WHERE id_spareparts='$jml[0]' ") or die (mysqli_error($conn));
$dataSP = mysqli_fetch_array($getData);
$idSpareparts = $dataSP[0];
$jmlStok = (int) $dataSP[0];
$jmlJual = (int) $jml[1];
$sisaStok = $jmlStok-$jmlJual;
$updateStok = mysqli_query($conn,"UPDATE data_spareparts SET jumlah_stok=$sisaStok WHERE id_spareparts='$jml[0]'") or die (mysqli_error($conn));
}
So I want to do "while($jml=mysqli_fetch_array($dataJumlah))" in C# and the rest of it. But how?
This question has been answered.
Below is the answer
subtotal = Convert.ToDouble(txtSubtotal.Text);
bayar = Convert.ToDouble(txtBayar.Text);
if (bayar < subtotal)
{
MessageBox.Show("Nominal yang dibayarkan lebih kecil dari Subtotal!");
}
else
{
openConnection();
string selectQuery = "SELECT * FROM data_pegawai WHERE is_deleted=0 AND username='" + user + "'";
MySqlCommand command1 = new MySqlCommand(selectQuery, conn);
MySqlDataReader reader1 = command1.ExecuteReader();
while (reader1.Read())
{
id = reader1.GetInt32("id_peg");
}
closeConnection();
kembali = bayar - subtotal;
lblKembali.Text = kembali.ToString();
string insertQuery1 = "UPDATE data_transaksi SET status_pengerjaan='Lunas',potongan_harga='" + diskonrupiah.ToString() + "',subtotal='" + txtSubtotal.Text + "' WHERE id_transaksi =" + int.Parse(txtID_T.Text);
string insertQuery2 = "INSERT INTO pegawai_onduty VALUES(NULL, '" + id + "','" + txtID_T.Text + "')";
openConnection();
string selectQuery1 = "SELECT dsp.id_spareparts, dtsp.JUMLAH_SPAREPART from data_transaksi dt LEFT JOIN detail_transaksi_sparepart dtsp ON dt.id_transaksi=dtsp.id_transaksi LEFT JOIN spareparts_motor sm ON dtsp.ID_SPAREPARTMOTOR=sm.ID_SPAREPARTMOTOR LEFT JOIN data_spareparts dsp ON sm.id_spareparts=dsp.id_spareparts where dtsp.id_transaksi =" + int.Parse(txtID_T.Text);
MySqlCommand command2 = new MySqlCommand(selectQuery1, conn);
MySqlDataReader reader2 = command2.ExecuteReader();
while (reader2.Read())
{
idSparepart = reader2.GetString(0);
jmlJual = reader2.GetInt32(1);
}
closeConnection();
openConnection();
string getData = "SELECT jumlah_stok FROM data_spareparts dsp WHERE id_spareparts='" + idSparepart + "'";
MySqlCommand command3 = new MySqlCommand(getData, conn);
MySqlDataReader reader3 = command3.ExecuteReader();
while (reader3.Read())
{
jmlStok = reader3.GetInt32(0);
}
closeConnection();
sisastok = jmlStok - jmlJual;
string updateStok = "UPDATE data_spareparts SET jumlah_stok = '" + sisastok + "' WHERE id_spareparts ='" + idSparepart + "'";
try
{
openConnection();
MySqlCommand command4 = new MySqlCommand(updateStok, conn);
if (command4.ExecuteNonQuery() == 1)
{
MessageBox.Show("Data berhasil disimpan!");
}
else
{
MessageBox.Show("Data tidak berhasil disimpan!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
closeConnection();
}
runQuery(insertQuery1);
runQuery(insertQuery2);
loadTransaksi();
}

How to insert a different selectedindex combobox value into database?

In my project i have a countries combobox (PaysCmBx0) that is filled from countries database table [Pays] column [pays], what i want to do is when i select a country in the combobox it insert the Alpha country code token from the Alpha country code column [Alpha2] in another table (exemple : United-states = US).
so when i select a country from the combobox it does nothing it's intserting the same value.
My table look like this:
[Aplha2] [Pays]
GB United Kingdom
IM Isle of Man
TZ United Republic Of Tanzania
US United States
BF Burkina Faso
UY Uruguay
UZ Uzbekistan
here's my code :
void Fillcombo()
{
string Query = "SELECT * FROM Pays";
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataReader myRead;
try
{
con.Open();
myRead = cmd.ExecuteReader();
while (myRead.Read())
{
string sName = myRead["Pays"].ToString();
PaysCmBx0.Items.Add(sName);
}
con.Close();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
private void AddBtn_Click(object sender, EventArgs e)
{
try
{
string Query = "INSERT INTO [dbo].[Adresses] ([idParent],[Type] ,[Adresse0],[Adresse1],[Adresse2],[CPT],[Ville],[Pays]) VALUES ('"+Contact.idContact+"','" + TypeAdrCmBx.Text+ "','" + this.AdrTxtBx0.Text + "','" + this.AdrTxtBx1.Text + "','" + this.AdrTxtBx2.Text + "','" + this.CptTxtBx.Text + "','" + this.VilleTxtBx.Text + "','" + this.PaysCmBx0.Text + "')";
SqlCommand cmd = new SqlCommand(Query, con);
con.Open();
SqlDataReader Read;
try
{
Read = cmd.ExecuteReader();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void PaysCmBx0_SelectedIndexChanged(object sender, EventArgs e)
{
string Query1 = "SELECT * FROM Pays WHERE Pays='" + PaysCmBx0.Text + "'";
SqlCommand cmd1 = new SqlCommand(Query1, con);
SqlDataReader myRead;
try
{
con.Open();
myRead = cmd1.ExecuteReader();
while (myRead.Read())
{
string Code_Pays = myRead["Alpha2"].ToString();
PaysCmBx0.SelectedIndex.Equals(Code_Pays);
}
con.Close();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
thanks every one i fund a solutions for this :
i create a function that gets the country code corresponding to what's selected in the combobox:
private string get_code_pays(string nom_pays)
{
string Query1 = "SELECT * FROM Pays WHERE Pays='" + PaysCmBx0.Text + "'";
string Code_Pays="";
SqlCommand cmd1 = new SqlCommand(Query1, con);
SqlDataReader myRead;
try
{
con.Open();
myRead = cmd1.ExecuteReader();
while (myRead.Read())
{
Code_Pays = myRead["Alpha2"].ToString();
PaysCmBx0.SelectedIndex.Equals(Code_Pays);
}
con.Close();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
return Code_Pays;
}
and then call my funtion with the parameter in my insert:
string Query = "INSERT INTO [dbo].[Adresses] ([idParent],[Type] ,[Adresse0],[Adresse1],[Adresse2],[CPT],[Ville],[Pays]) VALUES ('"+Contact.idContact+"','" + A + "','" + this.AdrTxtBx0.Text + "','" + this.AdrTxtBx1.Text + "','" + this.AdrTxtBx2.Text + "','" + this.CptTxtBx.Text + "','" + this.VilleTxtBx.Text + "','" + get_code_pays( this.PaysCmBx0.Text) + "')";

C# Message box multiple display in a row

I'm doing this code for list view to database i wanted to save all the columns, it saves but it display a messagebox in each row. Can somebody help me out to fix this i want to display only one messagebox when the button's click.
So here is my code
foreach (ListViewItem li in listView1.Items)
{
string condense = "datasource=localhost;port=3306;username=root;password=''";
string milk = "insert into cashier.sales(Cashier,Orders,Quantity,Size,Price,Date) values ('" + this.cashier.Text + "','" + li.SubItems[0].Text + "','" + li.SubItems[1].Text + "','" + li.SubItems[2].Text + "','" + li.SubItems[3].Text + "','" + this.dateTimePicker1.Value + "');";
MySqlConnection conDatabase = new MySqlConnection(condense);
MySqlCommand cmdDatabase = new MySqlCommand(milk, conDatabase);
MySqlDataReader myReader;
if (string.IsNullOrEmpty(cashier.Text))
{
MessageBox.Show("Please fill the Notes. ", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
conDatabase.Open();
myReader = cmdDatabase.ExecuteReader();
MessageBox.Show("Order has been added successfully ", "Order!", MessageBoxButtons.OK, MessageBoxIcon.Information);
total.Text = "";
amount.Text = "";
change.Text = "";
while (myReader.Read())
{
}
}
}
Move the MessageBoxoutside of your loop
foreach (ListViewItem li in listView1.Items)
{
string condense = "datasource=localhost;port=3306;username=root;password=''";
string milk = "insert into cashier.sales(Cashier,Orders,Quantity,Size,Price,Date) values ('" + this.cashier.Text + "','" + li.SubItems[0].Text + "','" + li.SubItems[1].Text + "','" + li.SubItems[2].Text + "','" + li.SubItems[3].Text + "','" + this.dateTimePicker1.Value + "');";
MySqlConnection conDatabase = new MySqlConnection(condense);
MySqlCommand cmdDatabase = new MySqlCommand(milk, conDatabase);
MySqlDataReader myReader;
if (string.IsNullOrEmpty(cashier.Text))
{
MessageBox.Show("Please fill the Notes. ", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
conDatabase.Open();
myReader = cmdDatabase.ExecuteReader();
total.Text = "";
amount.Text = "";
change.Text = "";
while (myReader.Read())
{
}
}
}
MessageBox.Show("Orders has been added successfully ", "Order!", MessageBoxButtons.OK, MessageBoxIcon.Information);

Trouble in C# inventory system update button

I have a problem in the form of my inventory system. Well it worked perfectly when one textbox was involved. But when there are 2 or more textbox involve it shows errors specifically: Truncated incorrect DOUBLE value: 'Knooks and Cranies'.
(Knooks and Cranies is an example of a supplier i inputted.)
I don't really know what's wrong because this is the 1st time I've encountered this error.
here's my code:
namespace SupplyRequestAndInventoryManagementSystem
{
public partial class DI_Assets : Form
{
connection con = new connection();
MySqlCommand cmd;
MySqlDataReader reader;
public DI_Assets()
{
InitializeComponent();
}
//load data from database
private void DI_Assets_Load(object sender, EventArgs e)
{
loadDepartment();
}
//checker
private void ListDelivery_SelectedIndexChanged(object sender, EventArgs e)
{
if (ListDelivery.SelectedItems.Count > 0)
{
ListViewItem itm = ListDelivery.SelectedItems[0];
lblAssetIDChecker.Text = itm.SubItems[4].Text;
}
}
//load data from supplier
private void btnSearch_Click(object sender, EventArgs e)
{
loadtbl();
}
//add button
private void btnAdd_Click(object sender, EventArgs e)
{
DialogResult dg = MessageBox.Show("Are you sure you want to add new Delivery Information?", "Message", MessageBoxButtons.YesNo);
if (dg == DialogResult.Yes)
{
if (SuppNameCombo.Text == "" || txtProdName.Text == "" || txtProdBrand.Text == "" || txtQty.Text == "" || DTPReceived.Text == "")
{
MessageBox.Show("Don't leave blanks!");
}
else
{
con.Close();
cmd = new MySqlCommand("Select * from deliver_mat where Del_MSupplier ='" + SuppNameCombo.Text + "' and Del_MName='" + txtProdName.Text + "' and Del_MBrand ='" + txtProdBrand.Text + "' and Del_MQty= '" + txtQty.Text + "' and Del_MReceived='" + DTPReceived.Text + "'", con.con);
con.Open();
reader = cmd.ExecuteReader();
if (reader.Read())
{
MessageBox.Show("Delivery Information already exist, sepcify a new one!");
}
else
{
addSection();
MessageBox.Show("Delivery Information successfully added!");
loadtbl();
txtProdName.Text = "";
txtProdBrand.Text = "";
txtQty.Text = "";
DTPReceived.Text = "";
}
}
}
else
{
MessageBox.Show("Adding new Delivery Information has been cancelled!");
}
}
//update button
private void btnUpdate_Click(object sender, EventArgs e)
{
DialogResult dg = MessageBox.Show("Are you sure you want to update the section?", "Message", MessageBoxButtons.YesNo);
if (dg == DialogResult.Yes)
{
if (SuppNameCombo.Text == "" && txtProdName.Text == "" && txtProdBrand.Text == "" && txtQty.Text == "" && DTPReceived.Text == "")
{
MessageBox.Show("Please choose section to be updated!");
}
else
{
updateSection();
MessageBox.Show("Section has been successfully updated!");
loadtbl();
SuppNameCombo.Text = "";
txtProdName.Text = "";
txtProdBrand.Text = "";
txtQty.Text = "";
DTPReceived.Text = "";
}
}
else
{
MessageBox.Show("Updating section has been cancelled!");
}
}
//----------------------------------------------------------------------------------------------
//Retrieving Data from DB to listview
void loadtbl()
{
con.Close();
DataTable table = new DataTable();
cmd = new MySqlCommand("Select * from deliver_assets where Del_ASupplier = '" + SuppNameCombo.Text + "'", con.con);
con.Open();
reader = cmd.ExecuteReader();
ListDelivery.Items.Clear();
while (reader.Read())
{
ListViewItem item = new ListViewItem(reader["Del_AName"].ToString());
item.SubItems.Add(reader["Del_ABrand"].ToString());
item.SubItems.Add(reader["Del_AReceived"].ToString());
item.SubItems.Add(reader["Del_AQty"].ToString());
item.SubItems.Add(reader["Del_aID"].ToString());
item.SubItems.Add(reader["Del_ASupplier"].ToString());
ListDelivery.Items.Add(item);
}
}
//Load Data to combo box
void loadDepartment()
{
con.Close();
DataTable table5 = new DataTable();
cmd = new MySqlCommand("Select Supp_Name from supply", con.con);
con.Open();
reader = cmd.ExecuteReader();
table5.Load(reader);
foreach (DataRow row in table5.Rows)
{
SuppNameCombo.Items.Add(row["Supp_Name"]);
}
}
//add function
void addSection()
{
con.Close();
cmd = new MySqlCommand("insert into deliver_assets(Del_AName, Del_ABrand, Del_AReceived, Del_AQty, Del_Asupplier) values('" + txtProdName.Text + "', '" + txtProdBrand.Text + "', '" + DTPReceived.Text + "', '" + txtQty.Text + "', '" + SuppNameCombo.Text + "')", con.con);
con.Open();
reader = cmd.ExecuteReader();
}
//update function
void updateSection()
{
con.Close();
cmd = new MySqlCommand("update deliver_assets set Del_ASupplier ='" + SuppNameCombo.Text + "' and Del_AName ='" + txtProdName.Text + "' and Del_ABrand ='" + txtProdBrand.Text + "' and Del_AQty ='" + txtQty.Text + "' and Del_AReceived ='" + DTPReceived.Text + "' where Del_aID ='" + lblAssetIDChecker.Text + "'", con.con);
con.Open();
reader = cmd.ExecuteReader();
}
}
}
Your code contains many errors that should be avoided in handling a database task:
Use of global variables for disposable object (in particular a
MySqlConnection)
No use of parameters
Incorrect syntax for the Update statement
Use of incorrect methods to Execute insert/update queries
Trying to use a do-it-all method to establish a connection (related
to first)
Thinking that a column with a specific datatype will happily accept a string as its value
To just give an example I will try to rewrite the Update code
//update function
void updateSection()
{
string cmdText = #"update deliver_assets
set Del_ASupplier =#sup.
Del_AName = #name,
Del_ABrand = #brand
Del_AQty = #qty
Del_AReceived = #recv
where Del_aID = #id";
using(MySqlConnection con = new MySqlConnection(.....))
using(MySqlCommand cmd = new MySqlCommand(cmdText, con))
{
cmd.Parameters.Add("#sup", MySqlDbType.VarChar).Value = SuppNameCombo.Text;
cmd.Parameters.Add("#name", MySqlDbType.VarChar).Value = txtProdName.Text;
cmd.Parameters.Add("#brand", MySqlDbType.VarChar).Value = txtProdBrand.Text;
cmd.Parameters.Add("#qty", MySqlDbType.VarChar).Value = Convert.ToDouble(txtQty.Text);
cmd.Parameters.Add("#recv", MySqlDbType.VarChar).Value = DTPReceived.Text;
cmd.Parameters.Add("#id", MySqlDbType.Int32).Value = Convert.ToInt32(lblAssetIDChecker.Text);
con.Open();
int rowsUpdated = cmd.ExecuteNonQuery();
if(rowUpdated > 0)
MessageBox.Show("Record updated");
}
}
Note that I can't be sure about the correct datatype of your columns. You should create the parameter with the DataType compatible for your column changing the MySqlDbType values shown in the example above.

How to insert rows into Mysql database without duplicate?

When i want to insert a row into my MySql database 4 rows will be inserted instead of 1. Could you help me?
MySqlConnection con = new MySqlConnection(cs);
string Query = "Insert Into csokolade (márka,ár,darab) values('" + this.Marka_Textbox.Text + "','" + this.Ar_Textbox.Text + "','" + this.Darab_Textbox.Text + "')";
MySqlCommand com = new MySqlCommand(Query, con);
com.ExecuteNonQuery();
EDIT: Here is the part of the code that has to insert the row:
try
{
MySqlConnection con = new MySqlConnection(cs);
con.Open();
int a = 0;
string q = "select count(*) from csokolade where márka='" + this.Marka_Textbox.Text + "';";
MySqlCommand com = new MySqlCommand(q, con);
try
{
a = Convert.ToInt32(com.ExecuteScalar());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
if (a == 0)
{
string Query = "Insert Into csokolade (márka,ár,darab) values('" + this.Marka_Textbox.Text + "','" + this.Ar_Textbox.Text + "','" + this.Darab_Textbox.Text + "')";
com = new MySqlCommand(Query, con);
com.ExecuteNonQuery();
}
else
{
MessageBox.Show("Ez a rekord már létezik!");
return;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

Categories