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?
Related
private void btn_Update_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update MyWeight set Weight='" + txt_Weight.Text + "'where Name='" + txt_Name.Text + "'";
string a = (string)cmd.ExecuteScalar();
con.Close();
if (a != null)
{
cmd.ExecuteNonQuery();
con.Close();
display_data();
MessageBox.Show("Weight updated successfuly!!!");
}
else
{
con.Close();
display_data();
MessageBox.Show("Not updated!!!");
}
}
I tried to update the weight into the database, but the database keeps saying that it is not updated.
Try like this:
bool updated;
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update MyWeight set Weight=#Weight where Name=#Name";
cmd.Parameters.Add(new SqlParameter("Weight", txt_Weight.Text));
cmd.Parameters.Add(new SqlParameter("Name", txt_Name.Text));
updated = (cmd.ExecuteNonQuery() > 1);
con.Close();
}
if (updated)
{
display_data();
MessageBox.Show("Weight updated successfuly!!!");
}
else
{
display_data();
MessageBox.Show("Not updated!!!");
}
It makes more sense to use ExecuteNonQuery for update operations in general because you don't expect any results.
Have you checked the table to see if it did update the row?
Why are you executing the same command with ExecuteNonQuery inside the if statement?
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.
this is my code for an update button which is supposed to update the database based on entry values of textboxes.I made the textboxes to be filled when user selects a row on datagridview.I want the user to simply click the row then change the textbox texts then click update.But i can't get this to work.All comments are helpful.Shoot.
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
if (txtOgrenciNo.Text.Length != 0 && txtAd.Text.Length != 0 && txtSoyad.Text.Length != 0 && txtEmail.Text.Length != 0 && txtTelefon.Text.Length != 0)
{
string query ="UPDATE ogrenci(studentId,name,lname,email,phone) SET (studentId=#studentId,name#name,lname=#lname,email=#email,phone=#phone) WHERE studentId=#studentId";
string query1 = "UPDATE loginusers(username,upassword) SET (username=#email,upassword=#phone) WHERE username=#email";
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
using (SqlCommand cmd = new SqlCommand(query1, connection))
{
connection.Open();
cmd.Parameters.AddWithValue("#emailVal", txtEmail.Text);
cmd.Parameters.AddWithValue("#phone", txtPhone.Text);
command.Parameters.AddWithValue("#studentId", txtStudentId.Text);
command.Parameters.AddWithValue("#name", txtName.Text);
command.Parameters.AddWithValue("#lname", txtLname.Text);
command.Parameters.AddWithValue("#email", txtEmail.Text);
command.Parameters.AddWithValue("#phone", txtPhone.Text);
cmd.ExecuteNonQuery();
command.ExecuteNonQuery();
populateGrid();
}
}
else
{
MessageBox.Show("Student Information can not be blank","Alert",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
}
catch (Exception)
{
MessageBox.Show("Please enter different student info", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
Change your update queries, remove (parameters) after table name
Change this lines
string query ="UPDATE ogrenci(studentId,name,lname,email,phone) SET (studentId=#studentId,name#name,lname=#lname,email=#email,phone=#phone) WHERE studentId=#studentId";
string query1 = "UPDATE loginusers(username,upassword) SET (username=#email,upassword=#phone) WHERE username=#email";
To this
string query ="UPDATE ogrenci SET studentId=#studentId,name#name,lname=#lname,email=#email,phone=#phone WHERE studentId=#studentId";
string query1 = "UPDATE loginusers SET username=#email,upassword=#phone WHERE username=#email";
I'm working with ASP.Net web application project . in my Registration form the Username and the Email will be check if it's exist in the database or not. but my problem is if the username and the Email are exist the user can register normally and his data will be added in the database! how i can stop it from adding these data and forced the user to change the username or the Email if one of them is exist ! please any help ?
my .aspx.cs page :
protected void Button1_Click(object sender, EventArgs e)
{
byte[] License;
Stream s = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(s);
License = br.ReadBytes((Int32)s.Length);
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString);
conn.Open();
string insertQuery = "insert into DeliveryMen (Name,Username,Password,Email,Phone,City,License) values (#name ,#username, #password, #email ,#phone ,#city,#License)";
SqlCommand com = new SqlCommand(insertQuery, conn);
com.Parameters.AddWithValue("#name", TextBoxName.Text);
com.Parameters.AddWithValue("#username", TextBoxUsername.Text);
com.Parameters.AddWithValue("#password", TextBoxPassword.Text);
com.Parameters.AddWithValue("#email", TextBoxEmail.Text);
com.Parameters.AddWithValue("#phone", TextBoxPhone.Text);
com.Parameters.AddWithValue("#city", DropDownList1.SelectedItem.ToString());
com.Parameters.AddWithValue("#License", License);
com.ExecuteNonQuery();
Response.Write("DONE");
conn.Close();
}
catch (Exception ex)
{ Response.Write("Error:" + ex.ToString()); }
}
protected void TextBoxUsername_TextChanged(object sender, EventArgs e)
{ // to check if the Username if exist
if (!string.IsNullOrEmpty(TextBoxUsername.Text))
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from DeliveryMen where Username=#Username", con);
cmd.Parameters.AddWithValue("#Username", TextBoxUsername.Text);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
checkusername.Visible = true;
imgstatus.ImageUrl = "NotAvailable.jpg";
lblStatus.Text = "UserName Already Taken";
System.Threading.Thread.Sleep(2000);
}
else
{
checkusername.Visible = true;
imgstatus.ImageUrl = "Icon_Available.gif";
lblStatus.Text = "UserName Available";
System.Threading.Thread.Sleep(2000);
}
}
else
{
checkusername.Visible = false;
}
}
protected void TextBoxEmail_TextChanged(object sender, EventArgs e)
{ // to check if the Email if exist
if (!string.IsNullOrEmpty(TextBoxEmail.Text))
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from DeliveryMen where Email=#email", con);
cmd.Parameters.AddWithValue("#Email", TextBoxEmail.Text);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
Div1.Visible = true;
Image1.ImageUrl = "NotAvailable.jpg";
Label2.Text = "the Email Already Taken";
System.Threading.Thread.Sleep(2000);
}
else
{
Div1.Visible = true;
Image1.ImageUrl = "Icon_Available.gif";
Label2.Text = "the Email Available";
System.Threading.Thread.Sleep(2000);
}
}
else
{
Div1.Visible = false;
}
}
Set unique constraints on your Username and email columns, your sql insert will throw an exception and you can handle that and notifiy the client accordingly.
See https://msdn.microsoft.com/en-GB/library/ms190024.aspx
use an insert stored procedure instead of inline insert query and in stored procedure before insert check where this username email id exist or not.
if (not exists(select 1 from DeliveryMen where Username= #Username and Email=#Email))
begin
insert into DeliveryMen (Name,Username,Password,Email,Phone,City,License) values (#name ,#username, #password, #email ,#phone ,#city,#License)
end
The primary key needs to be set in the database itself.
Suppose 'username' is your primary key and therefore unique. Then you can check whether it already exists in the database or not as follows:
private void button2_Click(object sender, EventArgs e
{
conn.Open();
com.Connection = conn;
sql = "SELECT COUNT(*) FROM lapusers WHERE [username] = #username";
com.CommandText = sql;
com.Parameters.Clear();
com.Parameters.AddWithValue("#username", userlapbox.Text);
int numRecords = (int)com.ExecuteScalar();
if (numrecords == 0)
{
sql = "INSERT INTO lapusers([username],[fillingcode],[branch],[department],[agency])VALUES(#username,#fillingcode,#branch,#department,#agency)";
com.CommandText = sql;
com.Parameters.Clear();
com.Parameters.AddWithValue("#username", userlapbox.Text);
com.Parameters.AddWithValue("#fillingcode", userfilllapbox.Text);
com.Parameters.AddWithValue("#branch", comboBox2.Text);
com.Parameters.AddWithValue("#department", comboBox1.Text);
com.Parameters.AddWithValue("#agency", comboBox3.Text);
com.ExecuteNonQuery();
MessageBox.Show("Created Successfully ..");
}
else
{
MessageBox.Show("A record with a user name of {0} already exists", userlapbox.Text);
}
conn.Close();
}
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();
}