Updating database from multiple textboxes - c#

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";

Related

asp.net C# prevent user from leaving any of the two dropdownlists empty

I am trying to update database table according to two dropdownlists value,
and I want to prevent the user from leaving any of the two dropdownlists empty
but the problem is it only check the first dropdownlist if it was empty
for example if I fill the first dropdownlist and left the second one empty it will update the update database table and will not prevent the user from leaving the second one empty
if(DropDownList_pc.SelectedItem.Value != "0" || DropDownList_laptop.SelectedItem.Value != "0")
if (DropDownList_pc.SelectedItem.Value == "1")
{
string sql = "update users_table set user_pc = 'yes'";
SqlCommand cmd1 = new SqlCommand(sql, sqlCon);
cmd1.ExecuteNonQuery();
cmd1.Dispose();
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "done');", true);
}
else if (DropDownList_pc.SelectedItem.Value == "2")
{
string sql = "update users_table set user_pc = 'no'";
SqlCommand cmd1 = new SqlCommand(sql, sqlCon);
cmd1.ExecuteNonQuery();
cmd1.Dispose();
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "done');", true);
}
if (DropDownList_laptop.SelectedItem.Value == "1")
{
string sql = "update users_table set user_laptop = 'yes'";
SqlCommand cmd1 = new SqlCommand(sql, sqlCon);
cmd1.ExecuteNonQuery();
cmd1.Dispose();
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "done');", true);
}
else if (DropDownList_laptop.SelectedItem.Value == "2")
{
string sql = "update users_table set user_laptop = 'no'";
SqlCommand cmd1 = new SqlCommand(sql, sqlCon);
cmd1.ExecuteNonQuery();
cmd1.Dispose();
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "done');", true);
}
}
else{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "you have to fill all feilds');", true);
}
If both of your dropdowns doesn't depend on each other you just need to fix your condition to use the AND operator like this:
if(DropDownList_pc.SelectedItem.Value != "0" && DropDownList_laptop.SelectedItem.Value != "0")

Button click does not change anything in database c#

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?

C# set database to specific data that I want

I am currently trying delete my advertisement. But instead of deleting it from database I just want to set the status from 1 ( which means active ) to 0 (which means inactive). I have tried to use query UPDATE. But I do not know the format. My current code is
protected void btnDelete_Click(object sender, EventArgs e)
{
if (sqlCon.State == ConnectionState.Closed)
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("DeleteImage", sqlCon);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("AdvID", Convert.ToInt32(hfContactID.Value));
sqlCmd.ExecuteNonQuery();
sqlCon.Close();
Clear();
FillGridView();
LitMsg.Text = "Deleted Successfully";
ButSave.Enabled = true;
Image1.Visible = false;
}
and I believe that Delete query does not change my status to 0 so my update query is something like this.
protected void btnUpdate_Click(object sender, EventArgs e)
{
if (FileImgsave.HasFile == true)
{
string imgfile = Path.GetFileName(FileImgsave.PostedFile.FileName);
//FileImgsave.SaveAs("Images/" + imgfile);
FileImgsave.SaveAs(Server.MapPath("~/Images/" + imgfile));
sqlCon.Open();
SqlCommand cmd = sqlCon.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE Advertisement SET Item=#item,ImgPath=#image,Name=#name Where AdvID='" + AdsTb.Text + "'";
cmd.Parameters.AddWithValue("#name", nameTb.Text);
cmd.Parameters.AddWithValue("#item", imgfile);
cmd.Parameters.AddWithValue("#image", "~/Images/" + imgfile);
cmd.ExecuteNonQuery();
sqlCon.Close();
FillGridView();
LitMsg.Text = "Update successfully!";
Clear();
}
Below is my delete query
ALTER PROC [dbo].[DeleteImage]
#AdvID int
AS
BEGIN
DELETE FROM Advertisement
WHERE AdvID = #AdvID
END
You forgot to Update the Status
cmd.CommandText = "UPDATE Advertisement SET Status=0, Item=#item,ImgPath=#image,Name=#name Where AdvID='" + AdsTb.Text + "'";
Status=0

How to stop adding duplicate username into database table?

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();
}

Datagridview update cell at certain condition

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();
}

Categories