Checking inventory, if exists - c#

I want to check if the the productID exist in the database and don't allow to update if the the productID does not exist
This is the code I used for checking
bool HasInventory()
{
foreach (ListViewItem item in lvMaterialsList.Items)
{
Label ltr = (Label)item.FindControl("Label1");
string name = ltr.Text;
bool existing = true;
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT ProductID FROM Inventory WHERE ProductID=" + name;
cmd.Parameters.AddWithValue("#ProductID", name);
SqlDataReader data = cmd.ExecuteReader();
if (data.HasRows)
existing = true;
else
existing = false;
con.Close();
return existing;
}
return false;
}
This is the code for the button used to update the database
protected void lvMaterialsList_ItemCommand(object sender, ListViewCommandEventArgs e)
{
bool existingSupply = IsExisting();
bool hasquantity = HasInventory();
Label ltRefNo = (Label)e.Item.FindControl("ltRefNo");
Label Label1 = (Label)e.Item.FindControl("Label1");
TextBox txtAlloted = (TextBox)e.Item.FindControl("txtAlloted");
Literal ltUsed = (Literal)e.Item.FindControl("ltUsed");
int alloted = Convert.ToInt32(txtAlloted.Text);
int productid = Convert.ToInt32(Label1.Text);
if (e.CommandName == "updateused")
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
if (existingSupply && hasquantity)
{
cmd.CommandText = "UPDATE RequiredMaterials SET Used=Used + #Used WHERE ReqMatID=#ReqMatID";
}
else
{
cmd.CommandText = "UPDATE RequiredMaterials SET Used=#Used WHERE ReqMatID=#ReqMatID";
}
cmd.Parameters.AddWithValue("#Used", alloted);
cmd.Parameters.AddWithValue("#ReqMatID", ltRefNo.Text);
cmd.ExecuteNonQuery();
cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "UPDATE Inventory SET Quantity = Quantity - #Quantity " +
"WHERE ProductID=#ProductID";
cmd.Parameters.AddWithValue("#Quantity", alloted);
cmd.Parameters.AddWithValue("#ProductID", productid);
cmd.ExecuteNonQuery();
con.Close();
}
GetMaterialsList();
}
I don't know why it keeps on updating..

Related

how to update datagridview after selecting row and changed in text box value and clicking update? which is connected to access db

i want to update the datagridview list after clicking on button update here is image
when i select raw heading its shows on textboxes and after changing the value and clicking update its showing msg record updated successfully. here's image.
but its not updating in datagridview..
private void UpdateButton_Click(object sender, EventArgs e)
{
if (ValueTextBox.Text != "" && TypeTextBox.Text != "")
{
cmd = new OleDbCommand("update Sflorotype set Sflorovalues=#value,Sflorotypes=#type where ID=#id", con);
con.Open();
cmd.Parameters.AddWithValue("#id", ID);
cmd.Parameters.AddWithValue("#value", ValueTextBox.Text);
cmd.Parameters.AddWithValue("#type", TypeTextBox.Text);
var returnValue =
cmd.ExecuteNonQuery();
MessageBox.Show("Record Updated Successfully");
con.Close();
DisplayData();
ClearData();
}
else
{
MessageBox.Show("Please Select Record to Update");
}
}
OleDbDataAdapter adapt;
private void DisplayData()
{
con.Open();
DataTable dt = new DataTable();
adapt = new OleDbDataAdapter("select * from Sflorotype", con);
adapt.Fill(dt);
dataGridViewList.DataSource = dt;
con.Close();
}
private void ClearData()
{
ValueTextBox.Text = "";
TypeTextBox.Text = "";
ID = 0;
}
private void dataGridViewList_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
ID = Convert.ToInt32(dataGridViewList.Rows[e.RowIndex].Cells[0].Value.ToString());
ValueTextBox.Text = dataGridViewList.Rows[e.RowIndex].Cells[1].Value.ToString();
TypeTextBox.Text = dataGridViewList.Rows[e.RowIndex].Cells[2].Value.ToString();
}
Sorry can't add comment - I am new here.
cmd = new OleDbCommand("update Sflorotype set Sflorovalues=#value,Sflorotypes=#type where ID=#id", con);
Are you sure as ID is 94? (at your image, there is ID 94) Because I don't see where you get this value.
I found ID only here, and you set it to 0:
private void ClearData()
{
ValueTextBox.Text = "";
TypeTextBox.Text = "";
ID = 0;
}
I see only here some ID value. And if you don't change it elsewhere, it will update ID with value 0.
You can easily get info what you are executing:
string command = "update Sflorotype set Sflorovalues=#value,Sflorotypes=#type where ID=#id";
MessageBox.Show(command);
cmd = new OleDbCommand(command, con);
EDIT:
try this in your UpdateButton_Click:
cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update Sflorotype set Sflorovalues=#value,Sflorotypes=#type where ID=#id";
cmd.Parameters.AddWithValue("#value", ValueTextBox.Text);
cmd.Parameters.AddWithValue("#type", TypeTextBox.Text);
cmd.Parameters.AddWithValue("#id", ID);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery(); {
MessageBox.Show("Record Updated Successfully");
con.Close();
}
DisplayData();
ClearData();
Parameters.AddWithValue("#id", ID) - this should be the last one in adding parameters.

Insert and Registration data not show in database table visual studio 2019

I'm making a enrollment system using visual studio 2019 and SQL server management studio 2008.When i tried to click insert button 'Inserted Successfully' and there's no errors.When i tried to click registration button 'Record Updated Successfully' and also there's no errors.But when i opened the database and refresh the database table there's no data in the data table.Any support for this issue much appreciated.
private void button2_Click(object sender, EventArgs e)
{
try
{
//taking data from the GUI
string ID = textBox1.Text;
string RegistrationNumber = textBox1.Text;
string StudentName = textBox2.Text;
string DateOfBirth = dateTimePicker1.Text;
String Age = textBox3.Text;
String Gender;
if (radioButton1.Checked == true)
{
Gender = "Male";
}
else
{
Gender = "Female";
}
string ContactNumber = textBox4.Text;
;
if (textBox1.Text == "" && textBox2.Text == "" && textBox3.Text == "" && textBox4.Text == "")
{
MessageBox.Show("Complete the Missing Data");
}
else if (comboBox1.SelectedItem == null)
{
MessageBox.Show("Click on the selected item after selecting a course");
}
else
{
string course = (comboBox1.SelectedItem != null) ? comboBox1.SelectedItem.ToString() : "";
MessageBox.Show("Student Inserted Successfully!!");
string constr = (ConfigurationManager.ConnectionStrings["dbo.Table_1"] != null) ? ConfigurationManager.ConnectionStrings["dbo.Table_1"].ConnectionString : "";
connection = new SqlConnection("Data Source=.\\(localdb)\\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
using (SqlConnection con = new SqlConnection(constr))
con.ConnectionString = constr;
}
if (con.State == ConnectionState.Closed)
con.Open();
SqlCommand com = new SqlCommand("INSERT INTO dbo.Table_1(ID, Registration Number, Student Name, Date of Birth, Age, Gender, Contact Number, Course Enrolled In) VALUES(#ID,#RegistrationNumber,#StudentName,#DateOfBirth,#Age,#Gender,#ContactNumber)", connection);
com.CommandType = CommandType.Text;
com.Connection = con;
com.CommandText = "SELECT * FROM dbo.Table_1 WHERE ID = #ID;";
com.Parameters.AddWithValue("#ID", textBox1.Text);
com.Parameters.AddWithValue("#RegistrationNumber", textBox1.Text);
com.Parameters.AddWithValue("#StudentName", textBox2.Text);
com.Parameters.AddWithValue("#DateOfBirth", dateTimePicker1.Text);
com.Parameters.AddWithValue("#Age", textBox3.Text);
com.Parameters.AddWithValue("#Gender", Gender);
com.Parameters.AddWithValue("#ContactNumber", textBox4.Text);
com.ExecuteNonQuery();
com.ExecuteReader();
com.Dispose();
}
catch
{
MessageBox.Show("Error");
}
finally
{
con.Close();
}
private void button6_Click(object sender, EventArgs e)
{
string ID = textBox1.Text;
if (ID == null) ;
if (textBox1.Text=="" || textBox2.Text=="" || textBox3.Text=="" || textBox4.Text=="")
{
MessageBox.Show("Please Enter Missing Details");
}
else
{
MessageBox.Show("Record Updated Successfully!!");
string constr = (ConfigurationManager.ConnectionStrings["dbo.Table_1"] != null) ? ConfigurationManager.ConnectionStrings["dbo.Table_1"].ConnectionString : "";
using (SqlConnection con = new SqlConnection(constr))
con.ConnectionString = constr;
if(con.State==ConnectionState.Closed)
{
con.Open();
}
String sql = "SELECT COUNT(*) AS [Count] FROM dbo.Table_1 WHERE ID =#ID";
SqlCommand cmd = new SqlCommand(sql, con) ;
cmd.Parameters.AddWithValue("#ID", ID);
int Id;
if (!int.TryParse(textBox1.Text, out Id))
{
// Report problem to your user
return;
}
SqlDataReader sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (sdr.Read())
{
if (Convert.ToInt32(sdr["count"]) == 1)
{
button2.Enabled = false;
button1.Enabled = true;
}
else
{
button2.Enabled = true;
button1.Enabled = false;
}
}
{
}
}
con.Close();
}
Based on my test, I find that you defined the SqlCommand.CommandText two times.
Please try to modify your code to the following.
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "insert into Student(ID,StudentName,DateOfBirth)values(#ID,#StudentName,#DateOfBirth)";
command.Parameters.AddWithValue("#ID", Convert.ToInt32(ID));
command.Parameters.AddWithValue("#StudentName", textBox2.Text);
command.Parameters.AddWithValue("#DateOfBirth", DateOfBirth
);
Also, please note that we should place the MessageBox.Show after the code com.ExecuteNonQuery();.
Here is a code example you could refer to, based on my test, it works well.
private void button1_Click(object sender, EventArgs e)
{
try
{
string ID = textBox1.Text;
string StudentName = textBox2.Text;
DateTime DateOfBirth = dateTimePicker1.Value;
string constr = "sttr";
SqlConnection connection = new SqlConnection(constr);
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "insert into Student(ID,StudentName,DateOfBirth)values(#ID,#StudentName,#DateOfBirth)";
command.Parameters.AddWithValue("#ID", Convert.ToInt32(ID));
command.Parameters.AddWithValue("#StudentName", textBox2.Text);
command.Parameters.AddWithValue("#DateOfBirth", DateOfBirth);
command.ExecuteNonQuery();
MessageBox.Show("success inserted");
connection.Close();
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
string ID = textBox1.Text;
string constr = "str";
SqlConnection connection = new SqlConnection(constr);
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "SELECT COUNT(*) AS [Count] FROM Student WHERE ID =#ID";
command.Parameters.AddWithValue("#ID", Convert.ToInt32(ID));
SqlDataReader sdr = command.ExecuteReader(CommandBehavior.CloseConnection);
while (sdr.Read())
{
if (Convert.ToInt32(sdr["count"]) == 1)
{
button2.Enabled = false;
button1.Enabled = true;
}
else
{
button2.Enabled = true;
button1.Enabled = false;
}
}
MessageBox.Show("Record Updated Successfully!!");
}
After the below line
com.connection = con;
add below code
com.executenonquery();

Why is my datagrid not updating after I update my database?

so I have this refresh and populate function here
private void Refresh()
{
MySqlCommand cmd = conn.CreateCommand();
String data, id, platenumber, brand, model, yearmodel, odometer;
cmd.CommandText = "SELECT * FROM vehicle";
cmd.CommandType = CommandType.Text;
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
id = reader.GetInt32(0).ToString();
platenumber = reader.GetString(1);
brand = reader.GetString(2);
data = $"{ id}/{ platenumber}/{ brand}";
}
reader.Close();
PopulateDataGrid();
}
private void PopulateDataGrid()
{
Form1 f1 = new Form1();
MySqlCommand cmd = conn.CreateCommand();
DataTable datatable = new DataTable();
cmd.CommandText = "select id,platenumber,brand,model,yearmodel,regdate,exdate,odometer from vehicle";
cmd.CommandType = CommandType.Text;
dataAdapter = new MySqlDataAdapter(cmd);
dataAdapter.Fill(datatable);
f1.dataGridView1.DataSource = datatable;
}
and this is my update function
private void savebtn_Click(object sender, EventArgs e)
{
Form1 f1 = new Form1();
int newid = Convert.ToInt32(idtxt.Text);
int ID = newid;
MySqlCommand cmd = new MySqlCommand("update vehicle set platenumber=#platenumber where ID = #id" , conn);
cmd.Parameters.AddWithValue("#id", ID);
cmd.Parameters.Add("#platenumber", MySqlDbType.VarChar, 10).Value = pnumber.Text;
cmd.Parameters.Add("#brand", MySqlDbType.VarChar, 60).Value = brand.Text;
cmd.Parameters.Add("#model", MySqlDbType.VarChar, 45).Value = model.Text;
cmd.Parameters.Add("#yearmodel", MySqlDbType.Int32).Value = yearmodel.Text;
//cmd.Parameters.Add("#regdate", MySqlDbType.Date).Value = datereg.MinDate;
//cmd.Parameters.Add("#exdate", MySqlDbType.Date).Value = regexp.MinDate;
cmd.Parameters.Add("#odometer", MySqlDbType.Decimal).Value = odometer.Text;
int i = cmd.ExecuteNonQuery();
if (i != 0)
{
MessageBox.Show("Success");
}
else
{
MessageBox.Show("Fail");
}
f1.Refresh();
this.Close();
}
the problem is when I click on the save button on FORM2 everything on the datagrid stays the same but when I click a refresh button from FORM1 with the same code it works. even if I put the function in FORM2 it still doesn't refresh the datagrid after I click the update button. what am I missing here?

Exits don't insert else insert

I have started to learn asp.net. I am using VS 2013 Express for C#.
How to make that a some if case to check a duplicate value and if this value is exists then I get a red summary about it and can't insert to DB else insert to database and too with update button.
Can you help?
SqlConnection con = new SqlConnection(#"Data Source=TSS\SQLEXPRESS;Initial Catalog=DB;Integrated Security=True");
protected void Add(object sender, EventArgs e)
{
var vardas = GridView1.FooterRow.FindControl("txtname") as TextBox;
var pavarde = GridView1.FooterRow.FindControl("txtlastname") as TextBox;
var pozymis = GridView1.FooterRow.FindControl("DropDownList2") as DropDownList;
SqlCommand comm = new SqlCommand();
comm.CommandText = "insert into asmenys (name,lastname, status) values(#name,#lastname, #status)";
comm.Connection = con;
comm.Parameters.AddWithValue("#name", name.Text);
comm.Parameters.AddWithValue("#lastname", lastname.Text);
comm.Parameters.AddWithValue("#status", status![enter image description here][1].Text);
con.Open();
comm.ExecuteNonQuery();
con.Close();
DataBind();
}
When you say check if a value exists, what fields should not have duplicates? Those are the fields you have to write a select statement for to check if they exist first.
Example
protected void Add(object sender, EventArgs e)
{
var vardas = GridView1.FooterRow.FindControl("txtname") as TextBox;
var pavarde = GridView1.FooterRow.FindControl("txtlastname") as TextBox;
var pozymis = GridView1.FooterRow.FindControl("DropDownList2") as DropDownList;
SqlCommand comm = new SqlCommand();
comm.CommandText = "select lastname from asmenys where lastname = #lastname";
comm.Parameters.AddWithValue("#lastname", lastname.Text);
SqlDataReader reader = comm.ExecuteReader();
if (reader.HasRows)
{
Console.WriteLine("Values exist");
}
else
{
comm.CommandText = "insert into asmenys (name,lastname, status) values(#name,#lastname, #status)";
comm.Connection = con;
comm.Parameters.AddWithValue("#name", name.Text);
comm.Parameters.AddWithValue("#lastname", lastname.Text);
comm.Parameters.AddWithValue("#status", status![enter image description here][1].Text);
con.Open();
comm.ExecuteNonQuery();
con.Close();
DataBind();
}
}

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

Categories

Resources