I have a particular part of an inventory interface that requires an employee to select his or her name from a combo box and then scan a product to the table assigned to the name of the employee.
My curiosity is: When hitting the EDIT, ADD OR DELETE button it knows what table to perform this function in from a Switch - Case statement with that employee name on it. The problem is, the piece of code is long for each employee, especially for 9 employees that each have a Switch - Case statement.
Any advice on how to simplify this or shorten the code? I do understand in advance about the parameterized SQL that I am failing to use. Just trying to accomplish this first.
private void btnAdd_Click(object sender, EventArgs e)
{
ActiveControl = txtSerialN;
if (!string.IsNullOrEmpty(txtSerialN.Text) && !string.IsNullOrEmpty(cboEmpName.Text))
switch (cboEmpName.SelectedItem.ToString().Trim())
{
case "John Doe":
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "INSERT INTO JohnDoe(SerialNumber,PartNumber,DateEntered,Customer) values ('" + txtSerialN.Text + "','" + txtPart.Text + "','" + txtDate.Text + "','" + txtCustomer.Text + "')";
command.ExecuteNonQuery();
MessageBox.Show("Inventory Added".PadLeft(23));
connection.Close();
txtSerialN.Clear();
txtPart.Clear();
txtDate.Clear();
txtCustomer.Clear();
command.CommandText = "SELECT * FROM JohnDoe ORDER BY PartNumber";
OleDbDataAdapter db = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
db.Fill(dt);
dataGridEmpParts.DataSource = dt;
}
catch (OleDbException)
{
string strmsg = "THIS SERIAL NUMBER ALREADY EXISTS ! , Please try again";
MessageBox.Show(strmsg, "YOU CAN'T ENTER THE SAME ONE AGAIN", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1);
connection.Close();
}
break;
}
}
I would rather put up a lookup table that will have columns such as EmployeeName, AssignedTable and dynamically construct the commandtext based on the parameter values.
I suspect this problem could more efficiently be fixed by altering the database. Perhaps even as simple as adding a field for employee name.
Related
I created a C# application to query and insert a product database. However I am here with a small doubt and if anyone can help me i thank you right away.
The following is:
I have a form to insert data into the database created in MS Access 2007, with the values of reference, sale number, client code, client name, quantity and position number in archive;
Here is my code until the moment:
private void btn_save_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=product.accdb");
OleDbCommand check_sn = new OleDbCommand("SELECT COUNT(*) FROM [product] WHERE ([sn] = #sn)", con);
OleDbCommand check_reference = new OleDbCommand("SELECT COUNT(*) FROM [product] WHERE ([reference] = #ref)", con);
OleDbCommand check_number = new OleDbCommand("SELECT COUNT(*) FROM [product] WHERE ([number] = #num)", con);
con.Open();
check_reference.Parameters.AddWithValue("#ref", textBox_ref.Text);
check_sn.Parameters.AddWithValue("#sn", textBox_sn.Text);
check_number.Parameters.AddWithValue("#num", textBox_num.Text);
int refExist = (int)check_reference.ExecuteScalar();
int SNExist = (int)check_sn.ExecuteScalar();
int numExist = (int)check_number.ExecuteScalar();
if (refExist > 0)
{
MessageBox.Show("A product with this reference already exists....!");
}
else if (SNExist> 0)
{
MessageBox.Show("A product with this sale number already exists....!");
}
else if (numExist > 0)
{
MessageBox.Show("A product with this archive number already exists....!");
}
else
{
try
{
String reference = textBox_ref.Text.ToString();
String sn = textBox_ov.Text.ToString();
String cod_client = textBox_cod.Text.ToString();
String client = textBox_cliente.Text.ToString();
String qtd = textBox_qtd.Text.ToString();
String number = textBox_num.Text.ToString(); //This will be the incremented number
String my_query = "INSERT INTO product(reference,sn,cod_client,client,qtd,number)VALUES('" + reference + "','" + sn + "','" + cod_client + "','" + client + "','" + qtd + "','" + number + "')";
OleDbCommand cmd = new OleDbCommand(my_query, con);
cmd.ExecuteNonQuery();
MessageBox.Show("Data saved successfully...!");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to" + ex.Message);
}
finally
{
con.Close();
}
cleanTextBoxes(this.Controls);
}
}
private void search_btn_Click(object sender, EventArgs e)
{
Form search = new Form_search();
search.Show();
this.Hide();
}
}
}
How can i make it so that instead of manually entering the position number in archive in the textbox it can be automatically filled with the new position in archive. For example, my last product inserted has the position 50 in archive, the new one will automatically be number 51 and so on ... and this number should appear automatically in the textbox so that the user knows what is the number of the new registered product.
Thank you,
Ok i have tried this and works but how i do now to increment this value +1?
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Aneis_Calibre.accdb");
con.Open();
OleDbDataReader myReader = null;
OleDbCommand number = new OleDbCommand("SELECT TOP 1 [number] FROM product Order by [number] desc", con);
myReader = number.ExecuteReader();
while (myReader.Read())
{
textBox_num.Text = (myReader["number"].ToString());
}
con.Close();
Inside your query, you would want to do something along these lines.
INSERT ...
OUTPUT inserted.identity_column
VALUES (...)
That will return a row with a value for the id. The identity column in SQL will always increment automatically for you. Which would alleviate your approach where you grab the last record and do:
int.TryParse(reader["..."]?.ToString(), out int id);
textbox.Text = id++;
By using the scalar, or reader though I would recommend scalar if you return a single column with a modified SQL query would result in the exact newly inserted id.
I'm still learning C#, I wanna ask about Update statement, I got a problem when updating data ... the process is success but data on database doesn't updated.. Did i do some mistake on this?
MySqlConnection con = new MySqlConnection("server=127.0.0.1;database=cproject;Uid=root;Pwd=admin");
MySqlDataAdapter oDA;
DataTable oDT = new DataTable();
MySqlCommand job;
private void button1_Click(object sender, EventArgs e)
{
job = new MySqlCommand("UPDATE barang SET Nama_barang = '"+txtNama+"' AND Jumlah_barang='"+txtStock+"' AND Harga_awal='"+txtBeli+"' AND Harga_jual='"+txtJual+"' WHERE ID = '"+txtIndex+"'", con);
try
{
con.Open();
job.ExecuteNonQuery();
MessageBox.Show("sukses");
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
did I do something wrong?
Few Instructions: You are trying the wrong syntax here for SQL UPDATE, IF you have to update more columns then each one should be separated with commas, not with AND, One more thing you have to take care of is that your code opens a wide door for hackers through injection, To close this door you have to use parameterized queries. Another thing( but not sure), The names txtNama, txtStock etc looks like the names of TextBoxes if so you have to use its .Text properties as well. if not use proper naming conventions.
In simple your code should be like the following:
MySqlCommand sqlCommand = new MySqlCommand("UPDATE barang SET Nama_barang =#Nama_barang,Jumlah_barang=#Jumlah_barang,Harga_awal=#Harga_awal,Harga_jual=#Harga_jual WHERE ID =#id", con);
sqlCommand.Parameters.AddWithValue("#Nama_barang", txtNama.Text);
sqlCommand.Parameters.AddWithValue("#Jumlah_barang", txtStock.Text);
sqlCommand.Parameters.AddWithValue("#Harga_awal", txtBeli.Text);
sqlCommand.Parameters.AddWithValue("#Harga_jual", txtJual.Text);
sqlCommand.Parameters.AddWithValue("#id", txtIndex.Text);
try
{
con.Open();
sqlCommand.ExecuteNonQuery();
MessageBox.Show("sukses");
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
You can try .Parameters.Add() if the values are of different types,
I believe you have the values coming in from TextBox as the Naming shows txtNama, txtStock So it should be txtNama.Text, txtStock.Text respectively. Another one which I believe it should be is that the Table in the DB would not be all Varchar Field. For Varchar field we need 'Value' but for int or numbers we should not be using 'value' whereas it should be value. So your Query should look like
"UPDATE barang SET Nama_barang = '" + txtNama.Text + "', Jumlah_barang=" + txtStock.Text + ", Harga_awal=" + txtBeli.Text + ", Harga_jual='" + txtJual.Text + "' WHERE ID = " + txtIndex.Text
I am not sure which of the fields are numeric. So I just removed '' for few which I think would be numeric. Now you should use Using Statement and Parameterized Query to care the SQL Injection. and thus your code would look like
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "UPDATE barang SET Nama_barang = #namabarang, Jumlah_barang = #Jumlahbarang, Harga_awal= #Hargaawal, Harga_jual=#Hargajual WHERE ID = #myID";
command.Parameters.AddWithValue("#namabarang", txtNama.Text);
command.Parameters.AddWithValue("#Jumlahbarang", txtStock.Text);
command.Parameters.AddWithValue("#Hargaawal", txtNama.Text);
command.Parameters.AddWithValue("#Hargajual", txtBeli.Text);
command.Parameters.AddWithValue("#myID", txtJual.Text);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}
Is there anything wrong with my code? It is not showing data in textboxes. The same funtion is working for another table in database but not for this one.
private void metroButton1_Click(object sender, EventArgs e)
{
con = new SqlConnection(constr);
String query = "Select FROM Student WHERE Std_ID = '" + metroTextBox1.Text + "'";
cmd = new SqlCommand(query, con);
con.Open();
try
{
using (SqlDataReader read = cmd.ExecuteReader())
{
while (read.Read())
{
// metroTextBox1.Text = (read["ID"].ToString());
metroTextBox2.Text = (read["Name"].ToString());
metroTextBox3.Text = (read["F_Name"].ToString());
metroTextBox4.Text = (read["Std_Age"].ToString());
metroTextBox5.Text = (read["Address"].ToString());
metroTextBox6.Text = (read["Program"].ToString());
metroComboBox1.Text = (read["Course"].ToString());
}
}
}
finally
{
con.Close();
}
}
you need to give column names in the select statement or select *
for example :
String query = "Select * from Student WHERE Std_ID = '" + metroTextBox1.Text + "'";
Not related to Question: you can change the while loop to if condition if you have one record for given id. even there are many records for given id you will see the last record data only because of the while loop will overwrite the textboxes in every record.
Update :
There isn't anything wrong with Syntax because the same syntax is
working for modifying teacher funtion.
No, this is incorrect, remove the try catch in your code then you will see the exception of syntax error
I am working on a project where the user is displayed a image with hotspots. Upon clicking one part he is displayed a dynamically generated checkbox for which the values are picked from database (hotspot are mapped to value displayed).
The problem I am facing is that when the value is a single word (ex. swelling) the code works fine and fetches the possible diseases, but when there are words like (ex. joint pain or nausea with vomiting) i.e the ones which contain space between them (more than one word as a checkbox value) the code does not work.
Here is the code
protected void Button2_Click(object sender, EventArgs e)
{
if (TextBox2.Text != "")
{
connection.Open();
symptons = String.Join(", ", CheckBoxList1.Items.Cast<ListItem>().Where(i => i.Selected).Select(i => i.Text).ToArray());
Label1.Text = symptons;
string query = symptons.Replace(", ", "','");
string cm = "select distinct dname from disease d inner join diseasesymptom ds on ds.did=d.did inner join symptom s on s.sid=ds.sid where s.sname in ('" + query + "')" + "and days >" + TextBox2.Text + " and days<41 order by (days) desc;";
if (symptons != "")
{
MySqlCommand cmd = new MySqlCommand(cm, connection);
using (MySqlDataAdapter sda = new MySqlDataAdapter())
{
cmd.Connection = connection;
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
else
{
Label1.Text = "select at least one symptom";
}
}
else
{
string script = "alert(\"We can't predict without all inputs :(\");";
ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script, true);
}
}
I think it has something to do with Join and Replace that I am performing.
never mind guys..I got it. I was missing a column value in database that helped in searching (hint : its 'days') . Anyway thanks for anyone who read this. :)
I'm trying to update my database records, but no changes are made and no error messages. I checked the syntax, the values I'm sending, everything is just fine ..
any suggestions?
This is my code which executed when [save] button is clicked:
ds.UpdateCommand = "UPDATE Users
SET Fullname='" + fname.Text + "',
Permission='" + per.SelectedValue + "',
Email='" + email.Text + "',
phone='" + phone.Text + "'
WHERE UserID=" + Session["userID"].ToString();
ds.Update();
I'm reading values from form filled by the user
ds is an SqlDataSource
If I have to add more details let me know
EDITS:
This page is for user to update his/her information
I'm setting the form values on Page_Load depending on the users information already exist in database.
the user edits his/her info and click [Save]
after setting braekpoints, I found that query string is taking the default values not the new ones. what should I do?
The entire code:
protected void Page_Load(object sender, EventArgs e)
{
Session["userID"] = Request.QueryString["id"];
SqlConnection cn = new SqlConnection();
cn.ConnectionString = ds.ConnectionString;
cn.Open();
SqlCommand cm = new SqlCommand();
cm.Connection = cn;
cm.CommandText = "select * from Users where UserID='" + Session["userID"].ToString() + "'";
SqlDataReader dr;
dr = cm.ExecuteReader();
if (dr.Read())
{
uname.Text = dr["username"].ToString();
fname.Text = dr["Fullname"].ToString();
per.SelectedValue = dr["Permission"].ToString();
email.Text = dr["Email"].ToString();
phone.Text = dr["phone"].ToString();
}
else Response.Redirect("Default.aspx");
dr.Close();
cn.Close();
}
protected void Button3_Click(object sender, EventArgs e)
{
ds.UpdateCommand = "update Users set Fullname='" + fname.Text + "', Permission='" + per.SelectedValue + "', Email='" + email.Text + "', phone='" + phone.Text + "' where UserID=" + Session["userID"].ToString();
ds.Update();
Response.Redirect("control_pan.aspx");
}
Basically, if you have a DataSet and you want to use that to update your database, you need to:
define the UpdateCommand as shown in the MSDN documentation to reference the columns from the DataTable which will be used to update
update an existing row in one of your DataTables inside the DataSet
once you've done that, then you can call .Update() on the data set (or data table) to execute the update - ADO.NET will check for updates to any of the rows of the DataTable, and if an update is found, then the UpdateCommand will be executed, with the parameters bound to the values of the DataTable's row in question
I would also recommend to read up on how the ADO.NET data model and using DataSets and DataTables works in detail - e.g. here Update Data Using .NET DataSets
The alternative, of course, would be to create a SqlConnection and a SqlCommand, using a parametrized query to do the insert yourself, without all the hassle and effort involved with DataSets and DataTables. But in that case, make sure to ALWAYS use parameterized queries (and NEVER just concatenate together your SQL statement including values straight from user input .....) - see why here
I suspect the Session["UserID"] is null. To check this set break point on ds.Update(); by putting the cursor on it then pressing F9.
To see the result query hover your mouse pointer over ds.UpdateCommand when break point pauses operation.
Update: put the code in the page load to be executed only once that is when first the page loads
if(!IsPostBack)
{
//put your code here
}
Update
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Session["userID"] = Request.QueryString["id"];
SqlConnection cn = new SqlConnection();
cn.ConnectionString = ds.ConnectionString;
cn.Open();
SqlCommand cm = new SqlCommand();
cm.Connection = cn;
cm.CommandText = "select * from Users where UserID='" + Session["userID"].ToString() + "'";
SqlDataReader dr;
dr = cm.ExecuteReader();
if (dr.Read())
{
uname.Text = dr["username"].ToString();
fname.Text = dr["Fullname"].ToString();
per.SelectedValue = dr["Permission"].ToString();
email.Text = dr["Email"].ToString();
phone.Text = dr["phone"].ToString();
}
else Response.Redirect("Default.aspx");
dr.Close();
cn.Close();
}
}
I seriously doubt you've provided enough details here to resolve the issue.
That type is UserID? Does the value need to be enclosed in quotes?
Are you setting the right value in your WHERE clause, and does that value existing in the database? You need to look at the resulting query string and then run it manually to determine what might be wrong.
Also, shouldn't you have the # character prefix for your string so that newlines are part of your string? Is this really what your code looks like?
Of course, without knowing more about the code, it's hard to say what else it might be as well.