I try to count Quantity of Products, how can I do this (in image)?I hope, you understood me. My code does'nt work.
This my code:
private void button1_Click(object sender, EventArgs e)
{
int i=1;
SqlCommand seldb = new SqlCommand("Select * from Product where barcode=" + textBox1.Text, conn);
conn.Open();
seldb.ExecuteNonQuery();
SqlDataReader read = seldb.ExecuteReader();
while (read.Read() == true)
{
dataGridView1.Rows.Add(read.GetValue(0), read.GetValue(1), read.GetValue(2), i);
for (int j=0;j<=dataGridView1.Rows.Count-1;j++)
{
if (textBox1.Text == dataGridView1.Rows[j].Cells[2].Value)
{
dataGridView1.Rows[j].Cells[3].Value = i;
}
}
i++;
}
conn.Close();
}
Not this:
How to do this?
Try altering your SQL query to aggregate your quantities.
Replace your command with this one.
SqlCommand seldb = new SqlCommand("Select ProductId, Name, Barcode, COUNT(*) as Quantity from Product where barcode =" + textBox1.Text + " Group By ProductId, Name, Barcode", conn);
You should actually be using a using statement with that as well.
Then you will replace your i values with the new Quantity column.
Note: Don't forget about Bobby Tables - http://bobby-tables.com/
Related
Here is my program:
What I want to do: when I enter 1 in ProductID textbox, I want category, name and price for ProductID = 1 to be filled into their textboxes.
I have tried to read from product table where ProductID = ProductIDTB.Text and then changed the other textboxes to show the data inside the other columns
Here is my code when ProductID textbox is changed:
protected void ProductIDTB_TextChanged(object sender, EventArgs e)
{
string connectionString1;
SqlConnection cnn1;
connectionString1 = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Greenwich_Butchers;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
cnn1 = new SqlConnection(connectionString1);
string selectSql1 = "SELECT * FROM [Product] WHERE ProductID = ('" + Convert.ToInt32(ProductIDTB.Text) + "') ";
SqlCommand com1 = new SqlCommand(selectSql1, cnn1);
try
{
cnn1.Open();
using (SqlDataReader read = com1.ExecuteReader())
{
while (read.Read())
{
String productcategory = Convert.ToString(read["ProductCategory"]);
ProductCategoryTB.Text = productcategory;
String productname = Convert.ToString(read["ProductName"]);
ProductNameTB.Text = productname;
String productprice = Convert.ToString(read["ProductPrice"]);
ProdPriceTB.Text = productprice;
}
}
}
catch (Exception ex)
{
Response.Write("error" + ex.ToString());
}
finally
{
cnn1.Close();
}
}
Work-around: as textbox_textchanged event was not working, I decided to add a button which finds product using the ID:
protected void FindProductBtn_Click(object sender, EventArgs e)
{
string connectionString1;
SqlConnection cnn1;
connectionString1 = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Greenwich_Butchers;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
cnn1 = new SqlConnection(connectionString1);
string selectSql1 = "SELECT * FROM [Product] WHERE ProductID = (" + Convert.ToInt32(ProductIDTB.Text) + ") ";
SqlCommand com1 = new SqlCommand(selectSql1, cnn1);
try
{
cnn1.Open();
using (SqlDataReader read = com1.ExecuteReader())
{
while (read.Read())
{
String productcategory = Convert.ToString(read["ProductCategory"]);
ProductCategoryTB.Text = productcategory;
String productname = Convert.ToString(read["ProductName"]);
ProductNameTB.Text = productname;
String productprice = Convert.ToString(read["ProductPrice"]);
ProdPriceTB.Text = productprice;
}
}
}
catch (Exception ex)
{
Response.Write("error" + ex.ToString());
}
finally
{
cnn1.Close();
ProductCategoryTB.ReadOnly = true;
ProductNameTB.ReadOnly = true;
ProdPriceTB.ReadOnly = true;
}
}
Set the textbox's AutoPostBack attribute to true
More info: https://meeraacademy.com/textbox-autopostback-and-textchanged-event-asp-net/
<asp:TextBox ID="ProductIDTB" runat="server" AutoPostBack="True"
OnTextChanged="ProductIDTB_TextChanged"></asp:TextBox>
By the way, use SqlParameter to use parameterized query. Aside from sql-injection attack prevention, parameterized query can help the RDBMS store and re-use the execution plan of similar queries, to ensure better performance. See: https://dba.stackexchange.com/questions/123978/can-sp-executesql-be-configured-used-by-default
string selectSql1 = "SELECT * FROM [Product] WHERE ProductID = #productIdFilter";
int productIdFilter = Convert.ToInt32(ProductIDTB.Text);
SqlCommand com1 = new SqlCommand(selectSql1, cnn1);
com1.Parameters.AddWithValue("productIdFilter", productIdFilter);
OnTextChanged Event in Code Behind
protected void txtProductId_TextChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["_connect"].ToString());
int ProductId = Convert.ToInt32(txtProductId.Text);
SqlCommand com = con.CreateCommand();
com.CommandText = "sp_ProductGetData";
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Mode", 1);
com.Parameters.AddWithValue("#ProductId", ProductId);
con.Open();
SqlDataReader dr = com.ExecuteReader();
if (dr.HasRows)
{
dr.Read();
txtProductCategory.Text = Convert.ToString(dr["ProductCategory"]);
txtProductName.Text = Convert.ToString(dr["ProductName"]);
txtPrice.Text = Convert.ToString(dr["Price"]);
}
else
{
ScriptManager.RegisterClientScriptBlock((Page)(HttpContext.Current.Handler), typeof(Page), "alert", "javascript:alert('" + Convert.ToString(("No Record Found with Prodcut Id: "+ProductId)) + "');", true);
return;
}
con.Close();
}
Stored Procedure
CREATE PROCEDURE sp_ProductGetData
(
#Mode INT=NULL,
#ProductId INT=NULL
)
AS
BEGIN
IF(#Mode=1)
BEGIN
SELECT ProductCategory,ProductName,Price FROM Product
WHERE ProductId=#ProductId
END
END
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.
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'm having troubles populating TextBoxes based on a ComboBox, Also insertion code won't work.
What should happen is, By selecting a customer from ComboBox, The details gets displayed on Text Boxes, And i can also add a customer to the ComboBox through the TextBoxes, Also there is a DataGridView displaying related info from another table based on my ComboBox selection but that's not the problem now.
Note:
I switched to Visual Studio 2012 recently, I'm assuming that's not a problem.
ComboBox exception:
An exception of type 'System.Data.SqlServerCe.SqlCeException' occurred in System.Data.SqlServerCe.dll but was not handled in user code.
Save button exception:
Input string was not in a correct format.
About the save button, The CustomerID is an Auto increment number, So i should be able to leave it's TextBox blank but it doesn't work when i do.
Table Structure:
Customers
CustomerID [int] [PK] [AutoNumber]
Name [nvarchar]
Phone1 [int]
Phone2 [int]
Address [nvarchar]
Notes [ntext]
Code:
private void FillCombo()
{
string code = "SELECT CustomerID, Name FROM Customers";
SqlCeDataAdapter da = new SqlCeDataAdapter(code, clsMain.con);
DataSet ds = new DataSet();
da.Fill(ds);
cBox1.DataSource = ds.Tables[0];
cBox1.DisplayMember = "Name";
cBox1.ValueMember = "CustomerID";
}
private void frmMain_Load(object sender, EventArgs e)
{
clsMain.con.Open();
FillCombo();
}
private void cBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string code = "SELECT * FROM Customers WHERE CustomerID='" + cBox1.Text + "'";
SqlCeDataAdapter da = new SqlCeDataAdapter(code, clsMain.con);
SqlCeCommandBuilder cmd = new SqlCeCommandBuilder(da);
DataSet ds = new DataSet();
da.Fill(ds);
if (cBox1.SelectedIndex > 0)
{
txt1.Text = ds.Tables[0].Rows[0]["CustomerID"].ToString();
txt2.Text = ds.Tables[0].Rows[0]["Name"].ToString();
txt3.Text = ds.Tables[0].Rows[0]["Phone1"].ToString();
txt4.Text = ds.Tables[0].Rows[0]["Phone2"].ToString();
txt5.Text = ds.Tables[0].Rows[0]["Address"].ToString();
txt6.Text = ds.Tables[0].Rows[0]["Notes"].ToString();
}
}
private void stripSave_Click(object sender, EventArgs e)
{
string code = "INSERT INTO Customers VALUES (#CustomerID, #Name, #Phone1, #Phone2, #Address, #Notes)";
SqlCeCommand cmd = new SqlCeCommand(code, clsMain.con);
cmd.Parameters.AddWithValue("#CustomerID", (txt1.Text); //Tried Parse and Convert.
cmd.Parameters.AddWithValue("#Name", txt2.Text);
cmd.Parameters.AddWithValue("#Phone1", txt3.Text);
cmd.Parameters.AddWithValue("#Phone2", txt4.Text);
cmd.Parameters.AddWithValue("#Address", txt5.Text);
cmd.Parameters.AddWithValue("#Notes", txt6.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Data stored.");
}
Sorry if it's a long code, But i thought it would be easier to spot the problems this way.
It seems like CustomerID is integral value, So you need to change
cmd.Parameters.AddWithValue("#CustomerID", txt1.Text);
to
cmd.Parameters.AddWithValue("#CustomerID", Int32.Parse(txt1.Text));
as per PhoenixReborn
if CustomerID is an auto increment, why are you trying to save it to the database? Kind of defeats the purpose.
then you need to edit your query to
string code = "INSERT INTO Customers(name, phone1, phone2, address, notes) VALUES (#Name, #Phone1, #Phone2, #Address, #Notes)";
SqlCeCommand cmd = new SqlCeCommand(code, clsMain.con);
cmd.Parameters.AddWithValue("#Name", txt2.Text);
cmd.Parameters.AddWithValue("#Phone1", txt3.Text);
cmd.Parameters.AddWithValue("#Phone2", txt4.Text);
cmd.Parameters.AddWithValue("#Address", txt5.Text);
cmd.Parameters.AddWithValue("#Notes", txt6.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Data stored.");
Try this instead:
private void stripSave_Click(object sender, EventArgs e)
{
int id;
string code;
SqlCeCommand cmd;
/*
If textbox is empty or input is not integer, then take the next id from table.
Otherwise, id is set to input value.
*/
if (txt1.Text == String.Empty || !int.TryParse(txt1.Text, out id))
{
/*
Selects max id + 1
If the table is empty, the result will be null
and coalesce will return 0 for the first id number
*/
code = "SELECT COALESCE((SELECT MAX(CustomerID) + 1 FROM Customers), 0);";
cmd = new SqlCeCommand(code, clsMain.con);
id = (int)cmd.ExecuteScalar();
}
code = "INSERT INTO Customers VALUES (#CustomerID, #Name, #Phone1, #Phone2, #Address, #Notes);";
cmd = new SqlCeCommand(code, clsMain.con);
cmd.Parameters.AddWithValue("#CustomerID", id);
cmd.Parameters.AddWithValue("#Name", txt2.Text);
cmd.Parameters.AddWithValue("#Phone1", txt3.Text);
cmd.Parameters.AddWithValue("#Phone2", txt4.Text);
cmd.Parameters.AddWithValue("#Address", txt5.Text);
cmd.Parameters.AddWithValue("#Notes", txt6.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Data stored.");
}
By the way, an important note about your code: Prefer to connect to database everytime you execute a query and close it afterwards. What I mean is that instead of keeping connection open for all the execution time, use something like this:
try
{
clsMain.con.Open();
cmd.ExecuteNonQuery();
clsMain.con.Close();
}
catch (Exception ex)
{
if (clsMain.con.State != ConnectionState.Closed)
clsMain.con.Close();
MessageBox.Show(ex.Message);
}
I want to filter rows on a datagrid on the basis of the textbox and I am using a stored procedure what should I do for that my code is following:
I wrote the query in stored procedure for selection is:
if #operation =1
select * from Item_Configuration where itemId like '%' + itemId + '%'
and C# code is
private void btnSrch_Click(object sender, EventArgs e)
{
SqlConnection conn1 = new SqlConnection();
try
{
SqlCommand selectItem = new SqlCommand("Item_Configuration_SP", conn1);
selectItem.CommandType = CommandType.StoredProcedure;
if (itemId.Text=="")
{
selectItem.Parameters.Add("#operation", SqlDbType.VarChar);
selectItem.Parameters["#operation"].Value = 1;
selectItem.Parameters.Add("#itemId", SqlDbType.VarChar);
selectItem.Parameters["#itemId"].Value = itmId.Text;
SqlDataReader myReader = selectItem.ExecuteReader();
List<Item> list = new List<Item>();
while (myReader.Read())
{
if (myReader.HasRows)
{
Item item = new Item();
item = MapItem(myReader, item);
list.Add(item);
}
}
dataGridView1.DataSource = list;
}
}
}
now i get all record on the grid the record is not filtering on the basis of textbox i cant find where i am wrong please help
Given that you are using Sql Server your query is worng
Instead of this
select * from Item_Configuration where itemId = '%' + itemId + '%'
It must be
select * from Item_Configuration where itemId LIKE '%' + itemId + '%'
Also you'll have to add this if you are getting operation id from textbox's input
selectItem.Parameters["#operation"].Value = txtbox.Text.Trim();