I have a datagrid with column id, nama barang, jumlah, harga
I used a textbox to input the data from database access, but i want update jumlah = jumlah + 1 whenever I inputed another id that already in the datagrid, but I got confused. Already try the for each row and for int count row things
this is my code
private void button_Input_Click(object sender, EventArgs e)
{
if (textBoxKodeBarang.Text != "")
{
insert_Data();
}
else if (textBoxKodeBarang.Text == "")
{
MessageBox.Show("Kode barang tidak boleh kosong !");
}
else
{
MessageBox.Show("Kode barang yang anda masukan salah !");
}
}
cmd.ExecuteNonQuery();
conn.Close();
}
private void insert_Data()
{
string cmdText = "Insert into [temp_Transaksi] (ID, nama_barang, harga) select id, nama, harga from [barang] where id =#pId";
OleDbConnection conn = new OleDbConnection(connString);
OleDbCommand cmd = new OleDbCommand(cmdText, conn);
cmd.Parameters.AddWithValue("#pId", textBoxKodeBarang.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
private void update_Data()
{
string cmdText = "Update [temp_Transaksi] set jumlah=jumlah+1 where id =#pId";
OleDbConnection conn = new OleDbConnection(connString);
OleDbCommand cmd = new OleDbCommand(cmdText, conn);
cmd.Parameters.AddWithValue("#pId", textBoxKodeBarang.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
Related
When I'm choosing additional (empty) position on Dropdownlist created by DropDownList.Item.Insert whole application is terminated.
if (!Page.IsPostBack)
{
DropDownList4.Items.Add(new ListItem("", ""));
DropDownList4.AppendDataBoundItems = true;
String strConnString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Projects\projects.accdb";
String strQuery = "select * from projects";
OleDbConnection con = new OleDbConnection(strConnString); ;
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
DropDownList4.DataSource = cmd.ExecuteReader();
DropDownList4.DataTextField = "Project_name";
DropDownList4.DataValueField = "ID";
DropDownList4.DataBind();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
}
protected void DropDownList4_SelectedIndexChanged(object sender, EventArgs e)
{
String strConnString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Projects\projects.accdb";
string strQuery = "select * from projects where" + " ID = #ID";
OleDbConnection con = new OleDbConnection(strConnString);
OleDbCommand cmd = new OleDbCommand();
cmd.Parameters.AddWithValue("#ID", DropDownList4.SelectedItem.Value);
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
OleDbDataReader myreader;
try
{
con.Open();
myreader = cmd.ExecuteReader();
myreader.Read();
TextBox12.Text = myreader["Project_name"].ToString();
TextBox2.Text = myreader["Owner"].ToString();
myreader.Close();
}
finally
{
con.Close();
}
}
As I'm thinking the reason is that the empty value does not exist in DB (but it is just created every time on Page_load by DropDownList4.Items.Add(new ListItem("", ""))). How to exclude from checking in DB first empty position on DropDownList?
Edited:
...
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
DropDownList4.DataSource = cmd.ExecuteReader();
if (DropDownList4.SelectedItem.Value == null || DropDownList4.SelectedItem == null)
{
}
DropDownList4.DataTextField = "Project_name";
DropDownList4.DataValueField = "ID";
DropDownList4.DataBind();
}
Still does not working
Edited:
string selected = DropDownList4.SelectedItem.Text;
if (string.IsNullOrEmpty(selected))
{
}
Now - It's working :)
You need (and want to) add the blank dropdown row AFTER you fill the dropdown.
So, say we have this markup:
<asp:DropDownList ID="DropDownList1" runat="server"
Height="26px" Width="207px" AutoPostBack="True"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
DataValueField="ID"
DataTextField="HotelName"
>
</asp:DropDownList>
And I DO suggest that you put the DataValue/Text settings in the control - really no need or advantage to putting that code in code behind.
And we don't need (or want) to re-load or re-insert the extra blank dropdown choice each time - so load the dropdown ONLY one time (the PostBack = false in page load as you attempted is correct).
So, we will select a hotel, and then pull that ONE database row for additional information - shove into a few text boxes as your code example does.
I suggest this code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string strSQL =
"SELECT ID, HotelName FROM tblHotels ORDER BY HotelName";
OleDbCommand cmdSQL = new OleDbCommand(strSQL);
DropDownList1.DataSource = MyRstP(cmdSQL);
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("- Select.. -", "0"));
}
}
DataTable MyRstP(OleDbCommand cmdSQL)
{
DataTable rstData = new DataTable();
using (OleDbConnection conn = new OleDbConnection(Properties.Settings.Default.AccessDB))
{
cmdSQL.Connection = conn;
using (cmdSQL)
{
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string HotelPK = DropDownList1.SelectedItem.Value as string;
string strSQL = "SELECT * FROM tblHotels where ID = #ID";
OleDbCommand cmdSQL = new OleDbCommand(strSQL);
cmdSQL.Parameters.Add("#ID", OleDbType.Integer).Value = HotelPK;
DataTable rstData = MyRstP(cmdSQL);
if (rstData.Rows.Count > 0)
{
DataRow OneRow = rstData.Rows[0];
TextBox1.Text = OneRow["HotelName"].ToString();
txtTaxRate.Text = OneRow["HotelTax"].ToString();
}
}
We also assume and have AutoPostBack = true for the drop list to fire each time we change it.
I'm currently practicing to make a barcode attendance application. After scanning the barcode, the barcode is automatically showing in a text box. There is a add button to send the barcode to the database. But when I click the add button only a blank dataset is adding.(It's working when directly type in the textbox)
private void VideoCaptureDevice_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)
{
Bitmap bitmap = (Bitmap)eventArgs.Frame.Clone();
BarcodeReader reader = new BarcodeReader();
var result = reader.Decode(bitmap);
if (result != null)
{
textBox1.Invoke(new MethodInvoker(delegate ()
{
textBox1.Text = result.ToString();
}));
}
pictureBox1.Image = bitmap;
}
Here is the add button code
private void button1_Click(object sender, EventArgs e)
{
cmd = new MySqlCommand();
cmd.CommandText = "insert into student_att (`id`, `nic`, `name`, `address`, `number`, `batch`) select* from student_dt where nibm_id like '" + textBox1.Text + "%'";
if (textBox1.Text == "")
{
MessageBox.Show("Please provide all data");
}
else
{
con.Open();
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Inserted");
string Query = "select * from student_att ;";
MySqlCommand MyCommand2 = new MySqlCommand(Query, con);
MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
MyAdapter.SelectCommand = MyCommand2;
DataTable dTable = new DataTable();
MyAdapter.Fill(dTable);
dataGridView2.DataSource = dTable;
}
try
{
textBox1.Text = string.Empty;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
1st of all, your queries are quite weird, when you do INSERT, I dont see anywhere what do you actually insert (no data specified in your code), it should be like:
private void button1_Click(object sender, EventArgs e)
{
if(textBox1.Text!=string.Empty)
{
//using means it will close and dispose the classes by it self! So no need to type Close() or Dispose() methods.
using (SqlConnection conn = new SqlConnection("ConnectionStringHere"))
{
bool bAllOK = false; //using and helping with some custom flag to get it all right
string query1 = #"INSERT INTO student_att (id, nic, name, address, number, batch) VALUES (#id, #nic, #name, #address, #number, #batch)";
string query2 = #"SELECT * FROM studetnt_att WHERE nibm_id LIKE #myText%";
//1. INSERT:
using (SqlCommand cmd = new SqlCommand(query1, conn))
{
cmd.Parameters.AddWithValue("#id", 1); //get new ID, best is to look for the last one in the DB, and increment by 1
cmd.Parameters.AddWithValue("#nic", "nickname1"); //get his nick name
//same way and and set all the other 4 parameters for name, address, number and batch here
try
{
connection.Open();
command.ExecuteNonQuery();
bAllOK = true;
}
catch(SqlException)
{
// error here if occures
}
}
if(bAllOK)
{
//2. SELECT:
using (SqlCommand cmd = new SqlCommand(query2, conn))
{
cmd.Parameters.AddWithValue("#myText", textBox1.Text);
DataTable table = new DataTable();
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(table);
dataGridView2.DataSource = table;
}
}
}
}
}
else
MessageBox.Show("Please type some name...");
}
The 2nd query makes no sence, since you are looking for nibm_id is looking for IDS which starts with the number in textBox. Is that really what you are looking for? LIKE SOMETHING% means that it looks for SOMETHINGS which starts with that.
I have a productstbl table consisting of Name,Quantity and other attributes.
When I want to buy a new item that is already present in productstbl table I need to update the Quantity.
SqlCommand cmdCount = new SqlCommand("SELECT COUNT(*) FROM Productstbl WHERE Name = #name", con);
con.Open();
cmdCount.Parameters.AddWithValue("#name", NameBox.Text);
int count = (int)cmdCount.ExecuteScalar();
con.Close();
if (count > 0)
{
SqlCommand cmd = new SqlCommand("SELECT Qunatity FROM Productstbl WHERE Name = #name, Quantity = #quantity", con);
con.Open();
cmd.Parameters.AddWithValue("#name", NameBox.Text);
int ExistingQTY = (int)cmdCount.ExecuteScalar(); // I get error here
}
cmd = new SqlCommand("INSERT INTO Historytbl (Name, Date, Price, Quantity, Total_Price, Sup_Name, Process, Retail_Price) VALUES (#name, #date, #price, #quantity, #total_price, #sup_name, #process, #retail_price)", con);
con.Open();
cmd.Parameters.AddWithValue("#name", NameBox.Text);
cmd.Parameters.AddWithValue("#date", dateTimePicker1.Text);
cmd.Parameters.AddWithValue("#price", PriceBox.Text);
cmd.Parameters.AddWithValue("#quantity", ExistingQTY);
cmd.Parameters.AddWithValue("#total_price", TotalPriceBox.Text);
cmd.Parameters.AddWithValue("#sup_name", comboBox1.Text);
cmd.Parameters.AddWithValue("#process", "buy");
cmd.Parameters.AddWithValue("#retail_price", RetailPriceBox.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record inserted successfully");
DisplayData();
ClearData();
If you want to update a quantity of a product, it is best for to get the quantity in the database if it already exists the database.
I make a code example, you can have a look.
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.Items.Add("Juice");
comboBox1.Items.Add("Apple");
comboBox1.Items.Add("Milk");
ShowData();
}
public void ShowData()
{
string connstr = "connstr";
SqlConnection connection = new SqlConnection(connstr);
connection.Open();
string cmd = "select * from Product";
DataSet set = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmd, connection);
adapter.Fill(set);
dataGridView1.DataSource = set.Tables[0];
}
private void button1_Click(object sender, EventArgs e)
{
string connstr = "connstr";
SqlConnection connection = new SqlConnection(connstr);
connection.Open();
SqlCommand cmdCount = new SqlCommand("SELECT COUNT(*) FROM Product WHERE Name = #Name", connection);
cmdCount.Parameters.AddWithValue("#Name", comboBox1.SelectedItem.ToString());
int count = (int)cmdCount.ExecuteScalar();
int i = 0;
if(count>0)
{
SqlCommand command = new SqlCommand("SELECT Quantity FROM Product WHERE Name = #Name",connection);
command.Parameters.AddWithValue("#Name", comboBox1.SelectedItem.ToString());
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
i = Convert.ToInt32(reader["Quantity"]);
}
}
SqlCommand updatecmd = new SqlCommand("Update Product set Quantity=#Quantity, Date=#Date where Name=#Name",connection);
updatecmd.Parameters.AddWithValue("#Quantity", i + numericUpDown1.Value);
updatecmd.Parameters.AddWithValue("#Date", DateTime.Now);
updatecmd.Parameters.AddWithValue("#Name", comboBox1.SelectedItem.ToString());
updatecmd.ExecuteNonQuery();
dataGridView1.DataSource = null;
ShowData();
MessageBox.Show("Update successfully");
}
else
{
SqlCommand insertcmd = new SqlCommand("insert into Product(Name,Quantity,Date,Price)values(#Name,#Quantity,#Date,#Price)",connection);
insertcmd.Parameters.AddWithValue("Name", comboBox1.SelectedItem.ToString());
insertcmd.Parameters.AddWithValue("#Quantity",numericUpDown1.Value);
insertcmd.Parameters.AddWithValue("#Date",DateTime.Now);
insertcmd.Parameters.AddWithValue("Price",Convert.ToInt32(textBox1.Text));
insertcmd.ExecuteNonQuery();
dataGridView1.DataSource = null;
ShowData();
MessageBox.Show("Insert successfully");
}
connection.Close();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if(comboBox1.SelectedItem.ToString()== "Juice")
{
textBox1.Text = "10";
}
if (comboBox1.SelectedItem.ToString() == "Apple")
{
textBox1.Text = "5";
}
if (comboBox1.SelectedItem.ToString() == "Milk")
{
textBox1.Text = "8";
}
}
Tested Result:
Button click when workorder exist to update the datatable does not change anything in the datatable but when the workorder does not exist it will insert data into the datatable. Does anyone know where i gone wrong? I have changed the update statement from my other post(Syntax error in update using C# inputting data into an existing row) when this problem(button click dont change anything) appears
private void save_care_Click(object sender, EventArgs e)
{
if (textBox2.Text=="")
MessageBox.Show("No data, Please scan workorder");
else
{
//Checking if workorder exist in database
connection.Open();
OleDbCommand checkrecord = new OleDbCommand("SELECT COUNT(*) FROM [c# barcode] WHERE ([Workorder] = #workorder)", connection);
checkrecord.Parameters.AddWithValue("#workorder", textBox2.Text);
int recordexist = (int)checkrecord.ExecuteScalar();
if (recordexist > 0)
{
//add data if it exist
string cmdText = "UPDATE [c# barcode] SET [Close from care] =#Close,[Name care] =#name WHERE[Workorder] = #workorder"; ;
using (OleDbCommand cmd = new OleDbCommand(cmdText, connection))
{
cmd.Parameters.AddWithValue("#workorder", textBox2.Text);
cmd.Parameters.AddWithValue("#Close", DateTime.Now.ToString("d/M/yyyy"));
cmd.Parameters.AddWithValue("#name", label4.Text);
cmd.ExecuteNonQuery();
textBox2.Clear();
connection.Close();
}
connection.Close();
}
else
{
//inserting workorder if it does not exist
string cmdText = "INSERT INTO [c# barcode] ([Workorder],[Close from care],[Name care]) VALUES (#workorder,#Close,#name)";
using (OleDbCommand cmd = new OleDbCommand(cmdText, connection))
{
cmd.Parameters.AddWithValue("#workorder", textBox2.Text);
cmd.Parameters.AddWithValue("#Close", DateTime.Now.ToString("d/M/yyyy"));
cmd.Parameters.AddWithValue("#name", label4.Text);
if (cmd.ExecuteNonQuery() > 0)
{
textBox2.Clear();
MessageBox.Show("Insert succesful, workorder has not been handedover, Please Check");
}
else
{
textBox2.Clear();
MessageBox.Show("Please rescan");
connection.Close();
}
connection.Close();
}
}
}
}
string cmdText = "UPDATE [c# barcode] SET [Close from care] =#Close,[Name care] =#name WHERE[Workorder] = #workorder"; ;
First check the double semicolon at this string doesn't the compiler complain?
Trying to update the first name of the student there is a textbox "FirstNameTextbox" information was loaded to it from the DB, when I change the information in the textbox and try to write the changes it read only the original data.So if it loaded "Craig" as the first name from the DB, i would edit and put "Chris" in the textbox, what happens is that Craig is written to the DB and not "Chris"
int stuID = getSqlStuID(IDNUMLabel.Text);
SqlConnection conn = new SqlConnection(GetConnectionString());
string sqlUpdateStudent = "Update tblStudent set fname = #fname where stuID = #stuID";
SqlCommand cmd = new SqlCommand(sqlUpdateStudent, conn);
conn.Open();
cmd.Parameters.AddWithValue("#stuID", stuID);
cmd.Parameters.AddWithValue("#fname", FirstNameTextbox.Text);
cmd.ExecuteNonQuery();
ErrorMessage.Text = "Success";
protected void Page_Load(object sender, EventArgs e)
{
if (Session["User"] != null)
{
IDNUMLabel.Text = Session["User"].ToString();
getStuData(Session["User"].ToString());
}
else
{
Response.Redirect("../Login/Login.aspx");
}
}
private void getStuData(string id)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "Select fname, sname From tblStudent Where idnumber = '" + id + "' ";
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
SqlDataReader selectedRecord = cmd.ExecuteReader();
cmd.CommandType = CommandType.Text;
while (selectedRecord.Read())
{
FirstNameTextbox.Text = selectedRecord["fname"].ToString();
LastNameTextbox.Text = selectedRecord["sname"].ToString();
}
selectedRecord.Close();
}
catch (System.Data.SqlClient.SqlException ex)
{
//id = 0;
//string msg = "Error reading Student ID";
//msg += ex.Message;
//throw new Exception(msg);
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
}
At what point do you make the actual update? After a button was pressed, after the value was entered on the textbox...? You're missing the method in which the code that handles the update is placed...
Maybe this could help: How to display data from database into textbox, and update it