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

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

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?

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 get each value in combobox over to sql database

Okay so here's my code. Everything works and saves to the database.
Though, it only stores the current value that's displayed in the combobox.
I want it to store all 3 values, for each value has its own checkboxes.
How would I go about coding something that saves each of the 3 values and the corresponding checkboxes to the database(sql)?
Form
, Code
private void button1_Click(object sender, EventArgs e)
{
if (con.State == ConnectionState.Closed)
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "insert into cloggingInfo(Date, PID, Operator, Type)values('"+labelTime.Text+"', '" + cboStatePid.Text + "', '" + cboStateOperator.Text + "', '" + cboStateType.Text + "')";
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
MessageBox.Show("Start added succesfully");
listView1.Items.Clear();
AddToListView();
}
}
Try to use "combobox.SelectedItem" or "combobox.SelectedValue". If your combobox is filled with datasource you need to define "DisplayMember" and "ValueMember" for it.
private void button1_Click(object sender, EventArgs e)
{
if (con.State == ConnectionState.Closed)
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "insert into cloggingInfo(Date, PID, Operator, Type)values('"+labelTime.Text+"', '" + cboStatePid.SelectedItem+ "', '" + cboStateOperator.SelectedItem+ "', '" + cboStateType.SelectedItem+ "')";
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
MessageBox.Show("Start added succesfully");
listView1.Items.Clear();
AddToListView();
}
}
Try to get the combo box items for each combo box as shown below and then save it.
private void button1_Click(object sender, EventArgs e)
{
StringBuilder comboBox1Items = new StringBuilder();
foreach (var item in comboBox1.Items)
{
comboBox1Items.Append(item + " ");
}
string cb1Items = comboBox1Items.ToString();
}

Trouble in updating database record in access with c#

I am working with a program which stores customers data
and later it needs to be changed
this is my code :
private void button2_Click(object sender, EventArgs e)
{
conn.Open();
string oc = ("Update Custs Set Cname =#Cname, NatCode=#NatCode, Bdate=#Bdate, CellPhone=#CellPhone, Addr=#Addr, Where NatCode Like'%" + textBox2.Text + "%'");
OleDbCommand myCommand = new OleDbCommand();
myCommand.CommandText = oc;
myCommand.Connection = conn;
myCommand.Parameters.AddWithValue("#Cname",textBox1.Text);
myCommand.Parameters.AddWithValue("#NatCode", textBox3.Text);
myCommand.Parameters.AddWithValue("#Bdate", textBox2.Text);
myCommand.Parameters.AddWithValue("#CellPhone", textBox4.Text);
myCommand.Parameters.AddWithValue("#Addr", textBox8.Text);
myCommand.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Data Changed successfully!");
}
But it doesn't do change anything
any help would be appreciated
Are you sure Where NatCode Like'%" + textBox2.Text + "%'" contains any row?
in myCommand.Parameters.AddWithValue("#Bdate", textBox2.Text); you are using textBox2 for Birthday and in Query you use it for NationalCode.
I guess the problem is it.

eliminating duplicate records insertion into database

The below is my code to insert gridview data into a database. However, using this I want to check and restrict insertion into the database where records have the same name, location, education and salary. If all of these are the same and those already present in database they should not get inserted. If any one column is different then they should get inserted.
protected void btn_insert_Click(object sender, EventArgs e)
{
foreach (GridViewRow g1 in GridView1.Rows)
{
SqlConnection con = new SqlConnection(connStr);
cmd = new SqlCommand("insert command", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
UploadStatusLabel.Text = "Records Inserted Successfully";
}
I think hitting the database inside a for loop is a very bad idea when you have other options. I'm not tackling this issue in the below sample.
Your code may be subject to SQL Injection, you need to use parameters to pass your values. If someone filled the input with ";DROP TABLE OpenOfficetext;" and they have DROP permissions, it will be a problem if you're just concatenating strings.
To avoid duplicates, you can check first if a similar record exists.
foreach (GridViewRow g1 in GridView1.Rows)
{
string insertCommand = "insert into OpenOfficetext(Name, Location, Education, Salary) values(#p1, #p2, #p3, #p4)";
string selectCommand = "SELECT COUNT(*) FROM OpenOfficetext WHERE Name = #p1 AND Location = #p2 AND Education = #p3 AND Salary = #p4";
SqlConnection con = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand(selectCommand, con);
con.Open();
cmd.Parameters.AddWithValue("#p1", g1.Cells[0].Text);
cmd.Parameters.AddWithValue("#p2", g1.Cells[1].Text);
cmd.Parameters.AddWithValue("#p3", g1.Cells[2].Text);
cmd.Parameters.AddWithValue("#p4", g1.Cells[3].Text);
if (Convert.ToInt32(cmd.ExecuteScalar()) == 0)
{
cmd.CommandText = insertCommand;
cmd.ExecuteNonQuery();
}
con.Close();
}
please use the below code
if not exist (select * from OpenOfficetext where Name='" + g1.Cells[0].Text + "' and Location='" + g1.Cells[1].Text + "' and Education = '" + g1.Cells[2].Text + "' and Salary = '" + g1.Cells[3].Text + "' )
Begin
SqlConnection con = new SqlConnection(connStr);
cmd = new SqlCommand("insert into OpenOfficetext(Name,Location,Education,Salary) values ('" + g1.Cells[0].Text + "','" + g1.Cells[1].Text + "','" + g1.Cells[2].Text + "','" + g1.Cells[3].Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
End

Categories