Adding an IF statement - c#

I wanted to add an if statement to this code that says..
IF i click this button , it will check if the ListU.SelectedValue is empty or not , and if it is empty , a messagebox saying "please pick a name before continuing" , and if it is not empty , the code then runs.
how do i do that?
this is the code for the button click. (i know , my code needs some parameter , we can ignore that for the moment)
private void button4_Click(object sender, EventArgs e)
{
//update code//
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
SqlDataAdapter daCount = new SqlDataAdapter("select iCount from ComDet where cName = #cName", conn);
daCount.SelectCommand.Parameters.Add("#cName", SqlDbType.VarChar).Value = ListU.SelectedValue;
DataTable dtC = new DataTable();
daCount.Fill(dtC);
DataRow firstRow = dtC.Rows[0];
string x = firstRow["iCount"].ToString();
int y = Int32.Parse(x);
int z = y + 1;
SqlCommand cmdC = conn.CreateCommand();
cmdC.CommandText = "Update ComDet set iCount = " + z + ", ViewTime = '" + lblTime.Text + "', LastView = '" + txtUser2.Text + "' Where cName = '" + ListU.SelectedValue.ToString() + "'";
cmdC.ExecuteNonQuery();
conn.Close();
var ufdet = new UserFullDetail(ListU.SelectedValue.ToString());
ufdet.ShowDialog();
}

private void button4_Click(object sender, EventArgs e)
{
if(ListU.SelectedValue == null || ListU.SelectedValue.ToString() == string.Empty)
{
MessageBox.Show("Select something from the listbox, please");
return;
}
.....

Try like this
private void button4_Click(object sender, EventArgs e)
{
if(ListU.SelectedValue == null || ListU.SelectedValue.ToString() == string.Empty)
{
MessageBox.Show("Select something from the listbox, please");
}
else
{
//update code//
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
SqlDataAdapter daCount = new SqlDataAdapter("select iCount from ComDet where cName = #cName", conn);
daCount.SelectCommand.Parameters.Add("#cName", SqlDbType.VarChar).Value = ListU.SelectedValue;
DataTable dtC = new DataTable();
daCount.Fill(dtC);
DataRow firstRow = dtC.Rows[0];
string x = firstRow["iCount"].ToString();
int y = Int32.Parse(x);
int z = y + 1;
SqlCommand cmdC = conn.CreateCommand();
cmdC.CommandText = "Update ComDet set iCount = " + z + ", ViewTime = '" + lblTime.Text + "', LastView = '" + txtUser2.Text + "' Where cName = '" + ListU.SelectedValue.ToString() + "'";
cmdC.ExecuteNonQuery();
conn.Close();
var ufdet = new UserFullDetail(ListU.SelectedValue.ToString());
ufdet.ShowDialog();
}
}

I prefer this:
private void button4_Click(object sender, EventArgs e)
{
if (ListU.SelectedItem == null)
{
MessageBox.Show("Please pick a name before continuing.");
}
else
{
// Run the code.
}
}
This makes the else condition explicit, rather than implied as in Steve's example.
Another approach would be to only enable button4 if something is selected in ListU, e.g.,
private void ListU_SelectedIndexChanged(object sender, System.EventArgs e)
{
button4.Enabled = ListU.SelectedItem != null;
}

Try this:
private void button4_Click(object sender, EventArgs e)
{
if(ListU.SelectedValue == null || string.IsNullOrEmpty(Convert.ToString(ListU.SelectedValue)))
{
MessageBox.Show("Select something from the listbox.");
return;
}
.....

Related

The data in my database does not show up in my data grid view

It does save in my database and it shows in data grid view but after I close and open it again it does not show my data from database to data grid view
public partial class Student : Form
{
private SQLiteConnection con;
private SQLiteCommand cmd;
private SQLiteDataAdapter DB;
private DataSet DS = new DataSet();
private DataTable DT = new DataTable();
public Student()
{
InitializeComponent();
LoadData();
}
string sql;
private void setConnection()
{
con = new SQLiteConnection("Data Source = library.db;Version = 3;New = false;Compress= true");
}
private void ExecuteQuery(string txtQuery)
{
setConnection();
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = txtQuery;
cmd.ExecuteNonQuery();
con.Close();
}
private void clearme()
{
txt_fname.Clear();
txt_lname.Clear();
txtAddress.Clear();
txtContact.Clear();
txtCourse.Clear();
}
private void LoadData()
{
setConnection();
con.Open();
cmd = con.CreateCommand();
string CommandText = "Select * From Student where BorrowerId='" + txtBid.Text + "'";
DB = new SQLiteDataAdapter(CommandText, con);
DS.Reset();
DB.Fill(DS);
DT = DS.Tables[0];
dtg_ABorrowLists.DataSource = DT;
}
/It does save in my database and it shows in data grid view but after I close and open it again it does not show my data from database to data grid view
private void btn_save_Click(object sender, EventArgs e)
{
string gender;
if (rdio_female.Checked)
{
gender = "Female";
}
else
{
gender = "Male";
}
string txtQuery = "insert into Student (`BorrowerId`, `Firstname`, `Lastname`, `Address`, "
+ "`Sex`, `ContactNo`, `CourseYear`)"
+ "values ('" + txtBid.Text + "','" + txt_fname.Text + "','" + txt_lname.Text
+ "','" + txtAddress.Text
+ "','" + gender + "','" + txtContact.Text + "','" + txtCourse.Text
+ "')";
ExecuteQuery(txtQuery);
LoadData();
}
private void txtBid_TextChanged(object sender, EventArgs e)
{
sql = "SELECT * FROM `tblborrower` WHERE `BorrowerId` = '" + txtBid.Text + "'";
if (DT.Rows.Count > 0)
{
txt_fname.Text = DT.Rows[0].Field<string>("Firstname");
txt_lname.Text = DT.Rows[0].Field<string>("Lastname");
txtAddress.Text = DT.Rows[0].Field<string>("Address");
txtContact.Text = DT.Rows[0].Field<string>("ContactNo");
txtCourse.Text = DT.Rows[0].Field<string>("CourseYear");
if (DT.Rows[0].Field<string>("Sex") == "Female")
{
rdio_female.Checked = true;
}
else
{
rdio_male.Checked = true;
}
btn_delete.Enabled = true;
}
else
{
btn_delete.Enabled = false;
clearme();
}
}
private void btn_delete_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Are you sure you want to delete this borrower?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
{
String txtQuery = "delete from Student where BorrowerId = '" + txtBid.Text + "'";
MessageBox.Show("Borrower has been deleted in the database.", "Success", MessageBoxButtons.OK);
ExecuteQuery(txtQuery);
LoadData();
}
}
private void btn_New_Click(object sender, EventArgs e)
{
this.clearme();
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
}
}

Why do i have question marks instead of text in DataGridView?

So i'm writing a program with C# and Sql, i created a database in visual studio and DataSet, and connected it to DataGridView. But the problem is, when i insert something into DataGridView row, all strings are presented as question marks, but with "int" type everything is okay.
namespace MH
{
public partial class PatientForm : Form
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Admin\source\repos\MH\MH\MH.mdf;Integrated Security=True");
public PatientForm()
{
InitializeComponent();
}
void populate()
{
conn.Open();
string query = "select * from Patient";
SqlDataAdapter da = new SqlDataAdapter(query, conn);
SqlCommandBuilder builder = new SqlCommandBuilder(da);
var ds = new DataSet();
da.Fill(ds);
PatientGV.DataSource = ds.Tables[0];
conn.Close();
}
private void label9_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void PatientForm_Load(object sender, EventArgs e)
{
populate();
PatientGV.Columns[0].HeaderText = "ID пациента";
PatientGV.Columns[1].HeaderText = "Имя";
PatientGV.Columns[2].HeaderText = "Адрес";
PatientGV.Columns[3].HeaderText = "Телефон";
PatientGV.Columns[4].HeaderText = "Возраст";
PatientGV.Columns[5].HeaderText = "Пол";
PatientGV.Columns[6].HeaderText = "Группа крови";
PatientGV.Columns[7].HeaderText = "Основная болезнь";
}
private void button4_Click(object sender, EventArgs e)
{
Home h = new Home();
h.Show();
this.Hide();
}
private void button2_Click(object sender, EventArgs e)
{
conn.Open();
string query = "update Patient set PatName = '" + PatName.Text + "', PatAddress = '" + PatAd.Text + "', PatPhone = '" + PatPhone.Text + "', PatAge = '" + PatAge.Text + "', PatGender = '" + GenderCb.SelectedItem.ToString() + "', PatBlood = '" + BloodCb.SelectedItem.ToString() + "', PatDisease = '" + MajorTb.Text + "' where PatId = '" + PatId.Text + "'";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.ExecuteNonQuery();
MessageBox.Show("Пациент успешно обновлен");
conn.Close();
populate();
}
private void PatientGV_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridViewRow row = this.PatientGV.Rows[e.RowIndex];
PatId.Text = row.Cells[0].Value.ToString();
PatName.Text = row.Cells[1].Value.ToString();
PatAd.Text = row.Cells[2].Value.ToString();
PatPhone.Text = row.Cells[3].Value.ToString();
PatAge.Text = row.Cells[4].Value.ToString();
MajorTb.Text = row.Cells[7].Value.ToString();
}
}
private void button1_Click(object sender, EventArgs e)
{
if (PatId.Text == "" || PatName.Text == "" || PatAd.Text == "" || PatPhone.Text == "" || PatAge.Text == "" || MajorTb.Text == "")
MessageBox.Show("Пустые поля не принимаются!");
else
{
conn.Open();
string query = "insert into Patient values(" + PatId.Text + ",'" + PatName.Text + "','" + PatAd.Text + "','" + PatPhone.Text + "'," + PatAge.Text + "," +
"'" + GenderCb.SelectedItem.ToString() + "','" + BloodCb.SelectedItem.ToString() + "','" + MajorTb.Text + "')";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.ExecuteNonQuery();
MessageBox.Show("Запись успешно добавлена!");
conn.Close();
populate();
}
}
private void button3_Click(object sender, EventArgs e)
{
if (PatId.Text == "")
MessageBox.Show("Введите ID пациента");
else
{
conn.Open();
string query = "delete from Patient where PatId=" + PatId.Text + "";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.ExecuteNonQuery();
MessageBox.Show("Пациент успешно удален");
conn.Close();
populate();
}
}
}
}
I'll be glad to any help!
Edit: added code of the form for clarification
You can try the following steps to solve the problem about question marks in the datagirdview.
First, you could create the following table in your database.
CREATE TABLE [dbo].[Patient] (
[Id] INT NOT NULL,
[Name] NVARCHAR (50) NOT NULL,
[Age] INT NOT NULL,
[Address] NVARCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
Second, Please try the following code to use SqlParameters to insert data to database.
SqlConnection conn = new SqlConnection(#"CONNSTR");
void populate()
{
conn.Open();
string query = "select * from Patient";
SqlDataAdapter da = new SqlDataAdapter(query, conn);
SqlCommandBuilder builder = new SqlCommandBuilder(da);
var ds = new DataSet();
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
conn.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
populate();
}
private void button1_Click(object sender, EventArgs e)
{
if (txtId.Text == "" || txtName.Text == "" || txtAge.Text == "" || txtAddress.Text == "" )
MessageBox.Show("Пустые поля не принимаются!");
else
{
conn.Open();
string query = "insert into Patient(Id,Name,Age,Address)values(#Id,#Name,#Age,#Address)";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("#Id",Convert.ToInt32(txtId.Text));
cmd.Parameters.AddWithValue("#Name", txtName.Text);
cmd.Parameters.AddWithValue("#Age", Convert.ToInt32(txtAge.Text));
cmd.Parameters.AddWithValue("#Address", txtAddress.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Запись успешно добавлена!");
conn.Close();
populate();
}
}
Result:

How to: Add a result to the same database as login

My app shows a menu of a restaurant where, after logging in with an email and password from the database, the client guides you to a computer that calculates Kcal after certain dates. I would like to be able to put the result in the same database and the same data that the client used as the image.
[
This is for an application I have for a contest
private void button1_Click(object sender, EventArgs e)
{
ani = Convert.ToInt32(textBox1.Text);
cm = Convert.ToInt32(textBox2.Text);
kg = Convert.ToInt32(textBox3.Text);
s = ani + cm + kg;
if (s < 250) label_mesaj.Text = "1800";
else if (s >= 250 && s <= 275) label_mesaj.Text = "2200";
else label_mesaj.Text = "2500";
}
private void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand cmd = new SqlCommand("insert into Clienti(parola,nume,prenume,adresa,email)values('" + textBox4.Text + "','" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox6.Text + "')", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
}
This is code that add to my database new clients after a registration, so i don't know how to remember that "id_clienti"
I expect that "label_mesaj" to show on the "kcal_zilnice" in the database after LogIn with the same data.
That's how I managed to solve the problem
The LogIn part that I remember the email
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constr);
SqlDataAdapter da = new SqlDataAdapter("Select count(*) from Clienti where email='" + textBox1.Text + "' and Parola='" + textBox2.Text + "'", con);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
client.email = textBox1.Text;
this.Hide();
Form4 ssss = new Form4();
ssss.Show();
}
else MessageBox.Show("verifica datele");
}
And in the next Form
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constr);
SqlDataAdapter da = new SqlDataAdapter();
con.Open();if (s < 250) label_mesaj.Text = "1800";
da.UpdateCommand = new SqlCommand("Update Clienti set kcal_zilnice= '" + label_mesaj.Text + "' where email= '" + Form3.client.email.ToString() + "'", con);
da.UpdateCommand.ExecuteNonQuery();
da.UpdateCommand.Dispose();
con.Close();
}

Archiving Customers In Access Database C#

I am trying to set up a method which allows me to archive a record which has been returned via a search box.
I have got the search query working however when I run the update query, the record still appears when searched for.
Can someone help?
namespace Test_Application
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
MainMenu MMform = new MainMenu();
MMform.Show();
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new
System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=BoilerSvc_be.mdb";
try
{
conn.Open();
OleDbCommand command = new OleDbCommand("SELECT Equipment.CustID AS CustID,Equipment.Manufacturer AS Manufacturer,Equipment.Model AS Model, Equipment.LastService AS LastService,Initial,Surname,[Address 1],[Address 2],[Address 3],[Post Town],[Post Code],Telephone FROM Contacts INNER JOIN Equipment ON Equipment.CustID = Contacts.CustID WHERE Contacts.Archived = 0 AND Surname = '" + textBox3.Text + "' OR Initial = '" + textBox3.Text + "' OR[Post Town] = '" + textBox3.Text + "' OR[Post Code] = '" + textBox3 + "'", conn);
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
int result;
customid.Text = reader["CustID"].ToString();
FirstName.Text = reader["Initial"].ToString();
LastName.Text = reader["Surname"].ToString();
Address1.Text = reader["Address 1"].ToString();
Address2.Text = reader["Address 2"].ToString();
Address3.Text = reader["Address 3"].ToString();
TownCity.Text = reader["Post Town"].ToString();
PostCode.Text = reader["Post Code"].ToString();
Telephone.Text = reader["Telephone"].ToString();
LstSvcDat.Text = reader["LastService"].ToString();
BoilMan.Text = reader["Manufacturer"].ToString();
BoilMod.Text = reader["Model"].ToString();
result = Convert.ToInt32(customid.Text);
}
}
finally
{
conn.Close();
}
}
private void button3_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(LastName.Text))
{
MessageBox.Show("Please Search for a Customer First");
}
else
{
System.Data.OleDb.OleDbConnection conn = new
System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=BoilerSvc_be.mdb";
try
{
conn.Open();
OleDbCommand command = new OleDbCommand("UPDATE Contacts SET Archived = 1 WHERE CustID = #CustID", conn);
command.Parameters.Add(new OleDbParameter("#PCustID", customid.Text));
OleDbDataReader reader = command.ExecuteReader();
}
finally
{
conn.Close();
customid.Text = null;
FirstName.Text = null;
LastName.Text = null;
Address1.Text = null;
Address2.Text = null;
Address3.Text = null;
TownCity.Text = null;
PostCode.Text = null;
Telephone.Text = null;
LstSvcDat.Text = null;
BoilMan.Text = null;
BoilMod.Text = null;
MessageBox.Show("Customer Archived");
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
I suspect the error is actually in your search query. When parenthesis are omitted the order of AND's and OR's are grouped. Try:
WHERE Contacts.Archived = 0 AND ((Surname = '" + textBox3.Text + "' OR Initial = '" + textBox3.Text + "') OR ([Post Town] = '" + textBox3.Text + "' OR[Post Code] = '" + textBox3 + "'))"

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.

Categories