C# set database to specific data that I want - c#

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

Related

how to update weight in database

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?

Why does database add null values although I am providing data?

I am inserting data in the textbox1 and dropdown1 but the data is only saved in the query which is written at the second position"i.e in this case c_name". C_name is either empty or inserts null values.
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
MySqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into market (m_name) values ('" + TextBox1.Text + "')";
cmd.CommandText = "insert into city (c_name) values('" + DropDownList1.SelectedValue + "')";
if (DropDownList1.SelectedValue == "-1")
{
Response.Write("Please select a city");
}
cmd.ExecuteNonQuery();
con.Close();
}
You should cmd.ExecuteNonQuery() after the first cmd.CommandText and then you have to do the same for your second cmd.CommandText, and both query will perform their actions.
protected void Button1_Click(object sender, EventArgs e)
{
if (DropDownList1.SelectedValue == "-1")
{
Response.Write("Please select a city");
return; // Must return don't execute after 'if' part or use 'else' there
}
con.Open();
MySqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into market (m_name) values ('" + TextBox1.Text + "')";
cmd.ExecuteNonQuery(); // First insert executed here
cmd.CommandText = "insert into city (c_name) values('" + DropDownList1.SelectedValue + "')";
cmd.ExecuteNonQuery(); // Second insert executed here
con.Close();
}

C# update query

I am finding error of No value given for one or required parameter C# update query where ever i try to update my c# access data base here is the code...
hope somebody will be of my assistant..
private void updatebutton_Click(object sender, EventArgs e)
{
try
{
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
string query = "update Emplyeedata set [ID]='" + midbox.Text + "',[Name]='" + mnamebox.Text + "',[Deisgnation]='" + mdesbox.Text + "',[Leave]='" + mleavebox.Text + "'Where [Name]='"+mnamebox.Text+"'";
cmd.CommandText = query;
cmd.ExecuteNonQuery();
con.Close();
cb();
MessageBox.Show("Updated", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch
{
MessageBox.Show("Error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
as a bit more improvement you can try like this, and if you can post the full error information.
private void updatebutton_Click()
{
using (OleDbConnection con = new OleDbConnection("Define your Connection String here"))
{
string query = #"UPDATE Emplyeedata
SET [id] = #ID
,[Name] = #Name
,[Deisgnation] = #Deisgnation
,[Leave] = #Leave
WHERE [Name] = #Name";
using (OleDbCommand cmd = new OleDbCommand(query, con) { CommandType = CommandType.Text })
{
cmd.Parameters.AddWithValue("#ID", midbox.Text);
cmd.Parameters.AddWithValue("#Name", mnamebox.Text);
cmd.Parameters.AddWithValue("#Deisgnation", mdesbox.Text);
cmd.Parameters.AddWithValue("#Leave", mleavebox.Text);
cmd.Parameters.AddWithValue("#Name", mnamebox.Text);
con.Open();
cmd.ExecuteNonQuery();
}
con.Close();
}
}
(this is a really unstructured way and please follow the SOLID Principle/s)

I have an inventory database in ASP.NET I want an error message if I try to decrease the stock by more than what is available

I have a website based inventory system, I can increase my stock and decrease it. however when I decrease it I want an error if you try to decrease it to -1.
For example: I have 40 stock on one item and I want to take away 41 it should give me a error message saying ERROR:NOT ENOUGH STOCK
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("update Inventory set stock = stock - '"
+ txtstockremove.Text + "' where model_number='" + txtmodelno.Text + "'", con);
cmd.ExecuteNonQuery();
con.Close();
GridView1.DataBind();
Label1.Visible = true;
Label1.Text = "Stock Successfully Removed!";
}
Picture of negative stock
I would suggest allowing the database to do what it does well. Add a constraint to your Inventory table so you can guarantee that the stock really will never go negative.
ALTER TABLE dbo.Inventory ADD CONSTRAINT CK_Inventory_Stock CHECK (Stock >= 0)
The side effect of this is that your cmd.ExecuteNonQuery() statement may well throw an exception. So you should really be prepared for that:
try {
cmd.ExecuteNonQuery();
GridView1.DataBind();
Label1.Visible = true;
Label1.Text = "Stock Successfully Removed!";
} catch (SqlException e) {
Label1.Visible = true;
Label1.Text = e.ToString();
}
If I understand the question correctly, you need to verify the stock before updating it:
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlDataReader reader;
SqlCommand cmd = new SqlCommand("select stock from Inventory, con);
cmd.CommandType = CommandType.Text;
reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here. You'll have to fill this part in
cmd.ExecuteNonQuery();
if (txtstockremove.Text <= currentStock)
{
SqlCommand cmd = new SqlCommand("update Inventory set stock= stock - '" + txtstockremove.Text + "' where model_number='" + txtmodelno.Text + "'", con);
cmd.ExecuteNonQuery();
}
else
{
Label1.Visible = true;
Label1.Text = "Stock Successfully Removed!";
}
con.Close();
GridView1.DataBind();
Label1.Visible = true;
Label1.Text = "Stock Successfully Removed!";
}

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

Categories