Below these code I'm getting the wrong output in incrementing the string value in my Database column "SupplierID". I'm transferring the string value to my lbl_id in ADDSupplier Form and That's what i used to insert value to my "SupplierID".
Desired Output:
SPPL-0001
SPPL-0002
SPPL-0003
etc
Currently Output (Below these code):
SPPL-0001
SPPL-00012
SPPL-00013
etc
NOTE: When i repeat inserting data i get the currently output that i stated above but when i restart the program and the last inserted value, For example is SPPL-00013. When i open my adding form, lbl_id display the id as SPPL-0004. If i continue, it become SPPL-00045.
PS: SupplierID is varchar(50) in my database and also PRIMARY_KEY
These image shows the wrong output of mine
What i want to get help with is to correct my logic and get that desired output. Please help me. Thank you
public partial class SIMSSupplier : UserControl
{
ADDSupplier supply;
public SIMSSupplier()
{
InitializeComponent();
}
public string ID = "SPPL-000";
public void GenerateAutoID()
{
using (var con = SQLConnection.GetConnection())
{
using (var select = new SqlCommand("Select Count(SupplierID) from admin_supplier", con))
{
int i = Convert.ToInt32(select.ExecuteScalar());
i++;
supply.lbl_id.Text = ID + i.ToString();
}
}
}
private void btn_register_Click(object sender, EventArgs e)
{
supply = new ADDSupplier(this);
supply.Show();
GenerateAutoID();
}
}
public partial class ADDSupplier : MetroForm
{
SIMSSupplier _view;
public ADDSupplier(SIMSSupplier _view)
{
InitializeComponent();
this._view = _view;
}
string date = DateTime.Now.ToString("MMMM-dd-yyyy");
private void btn_ok_Click(object sender, EventArgs e)
{
_view.ID = lbl_id.Text;
using (var con = SQLConnection.GetConnection())
{
if (string.IsNullOrEmpty(txt_name.Text) || string.IsNullOrEmpty(txt_contact.Text) || string.IsNullOrEmpty(cbox_remark.Text) || string.IsNullOrEmpty(txt_address.Text))
{
CustomNotifcation.Show("Please input the required fields", CustomNotifcation.AlertType.warning);
}
else
{
using (var select = new SqlCommand("Insert into admin_supplier (SupplierID, Companyname, Contactnumber, Date, Remarks, Address) Values (#SupplierID, #Companyname, #Contactnumber, #Date, #Remarks, #Address)", con))
{
select.Parameters.Add("#SupplierID", SqlDbType.VarChar).Value = lbl_id.Text;
select.Parameters.Add("#Companyname", SqlDbType.VarChar).Value = txt_name.Text;
select.Parameters.Add("#Contactnumber", SqlDbType.VarChar).Value = txt_contact.Text;
select.Parameters.Add("#Date", SqlDbType.VarChar).Value = date;
select.Parameters.Add("#Remarks", SqlDbType.VarChar).Value = cbox_remark.Text;
select.Parameters.Add("#Address", SqlDbType.VarChar).Value = txt_address.Text;
select.ExecuteNonQuery();
CustomMessage.Show("Message: Supplier successfully added!", CustomMessage.Messagetype.Success2);
_view._Supplier();
}
}
}
}
}
You just need to use a format string instead:
string ID = "SPPL-"
supply.lbl_id.Text = ID + i.ToString("0000");
Which will result in the format being applied correctly. Right now you are appending the i variable to the ID, which is already SPPL-000, so the next one becomes SPPL-0001, etc.
Related
I am trying to fetch the data in a decimal variable. I highly need your assistance to do so. if I test the query but put the fetched value in the label, it works without any problem. However, I want to get it in the decimal humidity as I want to compare this value with the threshold. Could you help me with this? Your help with being highly appreciated
below is the code
the output: I still get 20 which is the declared value in the code.
namespace IoTSmartFarming
{
public partial class DataVisualization : System.Web.UI.Page
{
string strcon = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
showHumidity();
}
private decimal getHumidity()
{
SqlConnection conn = new SqlConnection(strcon);
if (conn.State == System.Data.ConnectionState.Closed)
{
conn.Open();
}
decimal humidity = 20;
SqlCommand cmd = new SqlCommand("SELECT TOP 1 value from Humidity ORDER BY time desc", conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Label4.Text= dr.GetValue(0).ToString();
}
return humidity;
}
private void showHumidity()
{
decimal actHumidity = getHumidity();
Label4.Text = actHumidity.ToString();
if(actHumidity>100 || actHumidity < 10)
{
Label5.Visible = false;
Label6.Visible = true;
}
}
}
}
You forgot to assign your variable. All that you need is add an variable assignment:
humidity = dr.GetDecimal(0);
My issue can seem so trivial, but unfortunately I don't know how to solve that problem.
There's one table in one database. I have to add the data with clicking on the button to that table. When user clicks on the button, he's getting to some form where he/she can input the data. At the first time it would be good if I am able to input: id, kind of service, price. I've decided to create a new class where I would content all variables including these three variables. These variable are public.
Also I've decided to read the text from the textBoxes and to write this information to the variables of that class. In the second form there are 2 buttons. "Ok" and "Cancel". And I have decided to use ShowDialog.
I'm capable to output the table from the database to the DataGridView, but I am not well-aware how to add the data to my table and showcase that successfully in the datagridview after the inserting.
My class:
public class AllDataDB
{
public int id_serv;
public double price;
public string name;
}
The second form:
public partial class TypeService : Form
{
public AllDataDB Class;
public TypeService(AllDataDB t)
{
Class = t;
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
AllDataDB Class = new AllDataDB();
Class.id_serv = Convert.ToInt32(textBox3.Text);
Class.name = NameService.Text;
Class.price = Convert.ToDouble(PriceService.Text);
this.DialogResult = DialogResult.OK;
this.Close();
}
}
The work of the button calling the form and the query:
private void NewServe_Click(object sender, EventArgs e)
{
AllDataDB Class = new AllDataDB();
TypeService form = new TypeService(Class);
if (form.ShowDialog() == DialogResult.OK)
{ // відповідно до класу створюється новий запис. INSERT.
SqlConnection Con = new SqlConnection(connectionString);
Con.Open();
string Que = "INSERT INTO type_service " +
"VALUES(" + Class.id_serv + " ,'" + Class.name +
"' ," + Class.price + " );" +
"SELECT * FROM type_service";
SqlCommand cmd = new SqlCommand(Que, Con);
cmd.ExecuteNonQuery();
Con.Close();
SqlDataAdapter sqlDa = new SqlDataAdapter("SELECT * FROM type_service", Con);
DataTable d = new DataTable();
sqlDa.Fill(d);
dataGridView3.AutoGenerateColumns = false;
dataGridView3.DataSource = d;
}
}
There are many problems in the code shown. The most important ones are the way in which you read the values and how do you try to insert in the data. Inside the form TypeService you create a new instance of the AllDataDB class where you store the results. This instance is no more the one you have passed in input, so you need to read the values from the instance created by the TypeService form (stored in the global field Class). The second problem is the string concatenation of your values. This is a well known problem leading to parsing problems and sql injection. It is fixed by a parameterized query as shown below
private void NewServe_Click(object sender, EventArgs e)
{
// Do no pass an instance of Class here, just pass null
// or remove it at all if you don't plan to reuse the form for updating
TypeService form = new TypeService(null);
if (form.ShowDialog() == DialogResult.OK)
{
// Add the using statement to ensure a proper release of resources.
using SqlConnection Con = new SqlConnection(connectionString);
Con.Open();
// Parameterized query
string Que = "INSERT INTO type_service VALUES(#id,#name,#price);";
SqlCommand cmd = new SqlCommand(Que, Con);
cmd.Parameters.Add("#id", SqlDbType.Int).Value = form.Class.id_serv;
cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value = form.Class.name;
cmd.Parameters.Add("#price", SqlDbType.Decimal).Value = form.Class.price;
cmd.ExecuteNonQuery();
SqlDataAdapter sqlDa = new SqlDataAdapter("SELECT * FROM type_service", Con);
DataTable d = new DataTable();
sqlDa.Fill(d);
dataGridView3.AutoGenerateColumns = false;
dataGridView3.DataSource = d;
}
}
There are other minor problems. In the TypeService form and in the class AllDataDB you have used global fields instead of the more flexible way of using properties.
public class AllDataDB
{
public int id_serv {get;set;}
public double price {get;set;}
public string name {get;set;}
}
as well
public AllDataDB Class {get;set;}
also, given the null passed to the constructor of the TypeService form you now need to ensure to not use that Class properties without cheching for its null value
Well, this aid was very useful. Thanks. But I've resolved this problem with creating a new 3 variables in the class TypeService. These variables are public too. And that is looking like this:
In the class TypeService:
public int i;
public string n;
public double p;
In the class MainCore:
cmd.Parameters.Add("#id", SqlDbType.Int).Value = form.i;// form.Class.id_serv;
cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value = form.n;//form.Class.name;
cmd.Parameters.Add("#price", SqlDbType.Decimal).Value = form.p; //form.Class.price;
So it works. And I can remove the class AllDataDB, because that is not important and useful now.
Thanks for help.
I have a SQL Server database in C# [built before I got to my present job, creator is gone], and it was fine until last week. On the first page clerk_search.aspx it searches SQL Server for people and posts back to a datagrid that's fine.
There is a ASP Image button that's clicked on and it goes forward to the next page, to enter the reason the for the customers visit with loaded fields about the customer that post back. For some persons the next page populates, for others it does not. The SQL statement used checks out fine in query analyzer, I don't understand. I don't think its the reader because others are logged in fine, and the other customers are present in the rows in SQL and can be queried just fine. All is posted below, I am not savvy with coding, please assist.
System.InvalidOperationException: Invalid attempt to read when no data is present.
SqlDataReader reader2 = cmd.ExecuteReader();
reader2.Read();
[InvalidOperationException: Invalid attempt to read when no data is present.]
Here is the actual: ....clerk_create.aspx.cs
public partial class clerk_create : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Cookies["us"] == null)
{
Response.Write("Sorry, you do not have access to this page. Please see
data systems.");
Response.End();
}
if (!IsPostBack)
{
using (SqlConnection connection = new SqlConnection
(WebConfigurationManager.ConnectionStrings["walkin2"].ConnectionString))
{
TextBox txtsct = (TextBox)Page.PreviousPage.FindControl("Txtsct");
Txtsct.Text = txtsct.Text;
TextBox txt = (TextBox)Page.PreviousPage.FindControl("Txtssn");
Txtssn.Text = "" + txt.Text;
connection.Open();
string strsql2 = "SELECT dbo.table_name.SSN,
dbo.table_name.LAST_NAME,
dbo.table_name.FIRST_NAME, dbo.table_name.MIDDLE_INITIAL,
dbo.table_name.COMPONENT_CODE, dbo.table_name.PRESENT_CODE FROM
dbo.table_name INNER JOIN dbo.table_name ON dbo.table_name.SSN = '" +
Txtssn.Text + "')";
SqlCommand cmd = new SqlCommand(strsql2, connection);
SqlDataReader reader2 = cmd.ExecuteReader();
reader2.Read();
LblLName.Text = "" + reader2["LAST_NAME"];
LblFName.Text = "" + reader2["FIRST_NAME"];
}
}
}
...
}
You should check the return value of Read method.
If read method returns false then there is no more data. In that case you should not read the data from reader. Doing so will cause this exception.
If you're sure that you'll get only one record try this
if(reader2.Read())
{
LblLName.Text = "" + reader2["LAST_NAME"];
LblFName.Text = "" + reader2["FIRST_NAME"];
}
usually DataReader is used as below, since it can contain number of records
while (reader2.Read())
{
//Consume reader using reader2["Column"] etc
}
Your code is not properly disposing some objects and it is vulnerable to SQL injection.
DTO:
public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Code:
private static readonly Lazy<string> ConnectionString = new Lazy<string>(() => WebConfigurationManager.ConnectionStrings["walkin2"].ConnectionString);
private const string GetEmployeeBySSNQuery = "SELECT dbo.table_name.SSN, dbo.table_name.LAST_NAME, dbo.table_name.FIRST_NAME, dbo.table_name.MIDDLE_INITIAL, dbo.table_name.COMPONENT_CODE, dbo.table_name.PRESENT_CODE FROM dbo.table_name INNER JOIN dbo.table_name ON dbo.table_name.SSN = #SSN";
protected void Page_Load(object sender, EventArgs e)
{
// ...
if(!IsPostBack)
{
GetEmployeeInformation();
}
}
private void GetEmployeeInformation()
{
var sctTextBox = (TextBox)Page.PreviousPage.FindControl("Txtsct");
Txtsct.Text = txtsct.Text;
var ssnTextBox = (TextBox)Page.PreviousPage.FindControl("Txtssn");
Txtssn.Text = ssnTextBox.Text;
var ssn = ssnTextBox.Text;
var employee = GetEmployeeBySSN(ConnectionString.Value, ssn);
if(employee != null)
{
LblFName.Text = employee.FirstName;
LblLName.Text = employee.LastName;
}
}
private Employee GetEmployeeBySSN(string connectionString, string ssn)
{
Employee employee = null;
using(var connection = new SqlConnection(connectionString))
{
connection.Open();
using(var command = new SqlCommand(GetEmployeeBySSNQuery, connection)
{
command.Parameters.AddWithValue("#SSN", ssn);
using(var reader = command.ExecuteReader())
{
if(reader.Read())
{
employee = new Employee
{
FirstName = Convert.ToString(reader["FIRST_NAME"]),
LastName = Convert.ToString(reader["LAST_NAME"])
};
}
}
}
}
return employee;
}
hello every i was trying to create simple student form n add the data to the database but coudlnt do this, there was no error during the execution of the program, application executes nicely but no changes in the table, n the values are nt inserted into the table, what might b the problem plz suggest me, im writing my code below..
thanq in advance :)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace School.Project
{
class Student
{
public static string constr = System.Configuration.ConfigurationManager.ConnectionStrings"SchoolConnectionString"].ConnectionString;
public static int AddStudent(string title, string fname, string lname, string fathername, string gender, string clas, string sec, int age, string dob, string religion, string caste, string image, string address, string homeno, string cell, string email)
{
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlTransaction t = con.BeginTransaction();
SqlCommand cmd = new SqlCommand("INSERT INTO Student (Title,FirstName,LastName,FatherName,Gender,Class,Section,Age,DateOfBirth,Religion,Caste,Image,Address,HomePhone,CellPhone,Email) VALUES(#Title,#FirstName,#LastName,#FatherName,#Gender,#Class,#Section,#Age,#DateOFBirth,#Religion,#Caste,#Image,#Address,#HomePhone,#CellPhone,#Email)",con);
cmd.Parameters.AddWithValue("#Title", title);
cmd.Parameters.AddWithValue("FirstName", fname);
cmd.Parameters.AddWithValue("LastName", lname);
cmd.Parameters.AddWithValue("#FatherName", fathername);
cmd.Parameters.AddWithValue("#Gender", gender);
cmd.Parameters.AddWithValue("#Class", clas);
cmd.Parameters.AddWithValue("#Section", sec);
cmd.Parameters.AddWithValue("Age", age);
cmd.Parameters.AddWithValue("DateOfBirth", dob);
cmd.Parameters.AddWithValue("#Religion", religion);
cmd.Parameters.AddWithValue("Caste", caste);
cmd.Parameters.AddWithValue("Image", image);
cmd.Parameters.AddWithValue("Address", address);
cmd.Parameters.AddWithValue("#HomePhone", homeno);
cmd.Parameters.AddWithValue("#CellPhone", cell);
cmd.Parameters.AddWithValue("#Email", email);
cmd.Transaction = t;
int i = cmd.ExecuteNonQuery();
t.Commit();
con.Close();
return i;
}
private void btSave_Click(object sender, EventArgs e)
{
string title = cbTitle.SelectedItem.ToString();
string fname = txtfname.Text;
string lname = txtlname.Text;
string fathername = txtfatherName.Text;
string gender = cbGender.SelectedItem.ToString();
string clas = cbClass.SelectedItem.ToString();
string section = cbSection.SelectedItem.ToString();
int age = int.Parse(txtAge.Text);
string dob = txtdob.Text;
string religion = txtReligion.Text;
string caste = txtCaste.Text;
string imagepath = txtpath.Text;
string address = txtAddress.Text;
string homeno = txtHome.Text;
string cell = txtCell.Text;
string email = txtEMail.Text;
int i = Project.Student.AddStudent(title, fname, lname, fathername, gender, clas, section, age, dob, religion, caste, imagepath, address, homeno, cell, email);
if (i == 1)
{
MessageBox.Show("Student Added Succesfully, Thanq", "Inserted", MessageBoxButtons.OK, MessageBoxIcon.Information);
ClearAll();
}
else
{
MessageBox.Show("Couldnt enter the data", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
add a bracket [ ] on some fields of your query because some of the are reserved words:
SqlCommand cmd = new SqlCommand("
INSERT INTO Student ([Title],FirstName,LastName,
FatherName,Gender,
[Class],Section,Age,DateOfBirth,
Religion,Caste,[Image],Address,
HomePhone,CellPhone,Email)
VALUES(#Title,#FirstName,#LastName,
#FatherName,#Gender,#Class,#Section,
#Age,#DateOFBirth,#Religion,#Caste,
#Image,#Address,#HomePhone,
#CellPhone,#Email)",con);
[Title]
[Image]
UPDATED 1
Instead of SqlTransaction t = con.BeginTransaction();
try this:
SqlTransaction t = con.BeginTransaction(IsolationLevel.ReadCommitted)
Source: Use database transactions
Some of your parameters contain the "#" symbol and some don't....
1.) don't pass so many parameters. You want to add a STUDENT, that should ring all your bells. Pass only one parameter - class Student populated with the values you want.
2.) I don't think a transaction is necessary here. You want to push only one object, so if it fails, the result is the same - no changes done.
3.) as Daren said, you don't have properly written parameters in your query
EDIT:
Just tried the simplified version and it works like a charm... Here's the code:
Page.aspx.cs
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
btn.Click += new EventHandler(btn_Click);
}
void btn_Click(object sender, EventArgs e)
{
Student student = new Student() { Id = 1, Name = "John" };
int rowsAffected = Student.AddStudent(student);
Response.Write(rowsAffected);
}
}
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public static int AddStudent(Student s)
{
string conString = System.Configuration.ConfigurationManager.ConnectionStrings["string1"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Students (Name) VALUES (#Name)", con);
cmd.Parameters.AddWithValue("#Name", s.Name);
return cmd.ExecuteNonQuery();
}
}
}
Please, try to modify it to suit your needs and let me know, if it finally works. It has some problems (like not putting the class Student in a separate file), but I hope you get the idea.
I'm currently developing a POS system(windows application) in C# with SQL Server as the database. In my database, I have a product table that contains the following fields: barcode(primary key) , productID,productName ,productQty ,productSize, and productUnitPrice.
In my GUI, I have a TEXTBOX for the barcode, a numericUpDown for the quantity,and a LISTVIEW(7 columns : barcode, ID, Description, Quantity, Size, Regular Price, Sale Price) for the cart.
My problem is, how do I add the product information(barcode, productID, productName, productQty, productSize, productUnitPrice) inside the LISTVIEW based on the barcode that was entered on the barcode TEXTBOX?
//Inventory Base Class
public abstract class inventoryBaseClass
{
public inventoryBaseClass()
{
}
public inventoryBaseClass(uint _id)
{
Id = _id;
}
public void OpenSqlConn()
{
try
{
sqlConnection = #"Data Source=PC10\SQLEXPRESS;Initial Catalog=POSDB;Integrated Security=True";
sqlConn = new SqlConnection(sqlConnection);
sqlConn.Open();
}
catch (Exception ex)
{
DialogResult r = MessageBox.Show(ex.Message, "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
if (r == DialogResult.OK)
Application.Exit();
}
}
}
//Point of Sales Class
public class pointOfSalesClass : inventoryBaseClass
{
public pointOfSalesClass()
{
}
public pointOfSalesClass(uint _id)
: base(_id)
{
OpenSqlConn();
string sql = #"Select Barcode, ProductID, ProductName, TotalStocks,Size, Price, SaleAmount FROM PRODUCT WHERE Barcode = +" + _id;
SqlCmd = new SqlCommand();
SqlCmd.CommandText = sql;
SqlCmd.Connection = SqlConn;
}
}
//Point of sales Form
public partial class Point_of_Sales : Form
{
//these variables will hold the values that will be retreived in the SELECT statement in the Point of Sales Class
uint barcode = 0;
string id = "";
string productName = "";
uint qty = 0;
string size = "";
double regularPrice = 0.0;
double salePrice = 0.0;
//ADD to cart(Listview) Button
private void AddItem_Click(object sender, EventArgs e)
{
//the user enters the barcode on the txtBarcode textbox and the quantity to be purchased on the numericUpDown control
//When this button is pressed, the select statement will be executed
pointOfSalesClass addToCart = new pointOfSalesClass(uint.Parse(txtBarcode.Text.ToString()));
addToCart.SqlDataRdr = addToCart.SqlCmd.ExecuteReader();
uint quantity = Convert.ToUInt16(numericQty.Value);
while (addToCart.SqlDataRdr.Read())
{
//These are the values to be retreived
barcode = Convert.ToUInt32(addToCart.SqlDataRdr["Barcode"].ToString());
id = addToCart.SqlDataRdr["ProductID"].ToString();
productName = addToCart.SqlDataRdr["ProductName"].ToString();
qty = Convert.ToUInt32(addToCart.SqlDataRdr["TotalStocks"].ToString());
size = addToCart.SqlDataRdr["Size"].ToString();
regularPrice = Convert.ToDouble(addToCart.SqlDataRdr["Price"].ToString());
salePrice = Convert.ToDouble(addToCart.SqlDataRdr["SaleAmount"].ToString());
}
//After retreiving all values in the select statement
//How do I insert the values(barcode, id, productname, quantity(from the numericUpDown control), size, regularPrice,salePrice) inside the LISTVIEW.
}
}
This should get you started:
ListViewItem item = new ListViewItem(
new string[] { barcode.ToString(), id, productName /* etc */ });
listView1.Items.Add(item);
Basically, set your listview's itemssource to an empty list, and then fill that list with whatever items have THAT barcode, hook up the textchanged event of the textbox to update that list (Watch out for performance hits tho, use LINQ to objects instead of re-querying the DB)