Trying to update data in C# does not work - c#

I have a form which updates data. Query is executing but not updating the data. What's wrong? How to fix this?
It was working when I had concatenation but I changed it to parameters and now it's not working
private void button11_Click(object sender, EventArgs e)
{
try
{
if (SId.Text == "" || SellName.Text == "" || SellAge.Text == "" || SellPhone.Text == "" || SellPass.Text == "")
{
MessageBox.Show("Missing info");
}
string query = "UPDATE Sellers SET [SellerName] = #Name, [SellerAge] = #Age, [SellerPhone] = #Phone, [SellerPassword] = #Pass WHERE [SellerId] = #Id";
SqlCommand cmd = new SqlCommand(query, Con);
cmd.Parameters.AddWithValue("#Id", SId.Text);
cmd.Parameters.AddWithValue("#Name", SellName.Text);
cmd.Parameters.AddWithValue("#Age", SellAge.Text);
cmd.Parameters.AddWithValue("#Phone", SellPhone.Text);
cmd.Parameters.AddWithValue("#Pass", SellPass.Text);
Con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Update successful!");
SId.Text = "";
SellName.Text = "";
SellPhone.Text = "";
SellPass.Text = "";
SellAge.Text = "";
Con.Close();
populate();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

You have to use a connection for the shortest time possible. Instead of conection.Open() use cmd.connection.Open(). I recommend to use this code:
var result=0;
using (var con= new SqlConnection(connectionString))
{
var cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#Id", SId.Text); //??? if #Id is int or varchar?
cmd.Parameters.AddWithValue("#Name", SellName.Text);
cmd.Parameters.AddWithValue("#Age", SellAge.Text);
cmd.Parameters.AddWithValue("#Phone", SellPhone.Text);
cmd.Parameters.AddWithValue("#Pass", SellPass.Text);
cmd.Connection.Open();
result=cmd.ExecuteNonQuery();
}
if(result>0) MessageBox.Show("Update successful!");
else ....error
.... your code
I marked with ?? your #Id input parameter. I have some doubts that it is a string type. Check again. If it is int or any another type you will have to convert SId.Text to this type before to create a parameter.The same about #Age.

Related

Insert data from radio button into database

Building a form application in C# for selling phones as a project. I have two radio buttons which the user checks based on what type of payment method they want cash or card.
How do I insert that data into the database based on what the user selects?
You can try this,
protected void Button1_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["db"].ConnectionString;
SqlConnection cn = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into sample values(#payment)";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#payment", payment.SelectedValue);
if (cn.State == ConnectionState.Closed)
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
lblmsg.Text = "Data entered successfully!!!";
}
I found the answer to my own question if someone needs it
try
{
var connection = getConnection();
connection.Open();
if (CashRadio.Checked == true)
{
var command = new SqlCommand
{
Connection = connection,
CommandText ="INSERT INTO type_payment(cash,card) values(1,0)"
};
command.Parameters.Clear();
int result = command.ExecuteNonQuery();
if (result > 0)
{
MessageBox.Show("Succsefully picked type");
}
else
{
MessageBox.Show("error");
}
}
else if (CardRadio.Checked == true)
{
var command = new SqlCommand
{
Connection = connection,
CommandText = "INSERT INTO type_payment(cash,card) values(0,1)"
};
command.Parameters.Clear();
int result = command.ExecuteNonQuery();
if (result > 0)
{
MessageBox.Show("Succesfully picked type");
}
else
{
MessageBox.Show("Error");
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Luka,
Try it below.
Add HTML Markup like:
<asp:CheckBox ID="chkCash" runat="server" />
.cs file add below code.
string Cash = chkCash.Checked ? "Y" : "N";
And send or add value like.
SqlCommand cmd = new SqlCommand("INSERT INTO Employees(Cash) VALUES(#Cash)"))
{
cmd.Parameters.AddWithValue("#Cash", Cash);
}

Insert and Registration data not show in database table visual studio 2019

I'm making a enrollment system using visual studio 2019 and SQL server management studio 2008.When i tried to click insert button 'Inserted Successfully' and there's no errors.When i tried to click registration button 'Record Updated Successfully' and also there's no errors.But when i opened the database and refresh the database table there's no data in the data table.Any support for this issue much appreciated.
private void button2_Click(object sender, EventArgs e)
{
try
{
//taking data from the GUI
string ID = textBox1.Text;
string RegistrationNumber = textBox1.Text;
string StudentName = textBox2.Text;
string DateOfBirth = dateTimePicker1.Text;
String Age = textBox3.Text;
String Gender;
if (radioButton1.Checked == true)
{
Gender = "Male";
}
else
{
Gender = "Female";
}
string ContactNumber = textBox4.Text;
;
if (textBox1.Text == "" && textBox2.Text == "" && textBox3.Text == "" && textBox4.Text == "")
{
MessageBox.Show("Complete the Missing Data");
}
else if (comboBox1.SelectedItem == null)
{
MessageBox.Show("Click on the selected item after selecting a course");
}
else
{
string course = (comboBox1.SelectedItem != null) ? comboBox1.SelectedItem.ToString() : "";
MessageBox.Show("Student Inserted Successfully!!");
string constr = (ConfigurationManager.ConnectionStrings["dbo.Table_1"] != null) ? ConfigurationManager.ConnectionStrings["dbo.Table_1"].ConnectionString : "";
connection = new SqlConnection("Data Source=.\\(localdb)\\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
using (SqlConnection con = new SqlConnection(constr))
con.ConnectionString = constr;
}
if (con.State == ConnectionState.Closed)
con.Open();
SqlCommand com = new SqlCommand("INSERT INTO dbo.Table_1(ID, Registration Number, Student Name, Date of Birth, Age, Gender, Contact Number, Course Enrolled In) VALUES(#ID,#RegistrationNumber,#StudentName,#DateOfBirth,#Age,#Gender,#ContactNumber)", connection);
com.CommandType = CommandType.Text;
com.Connection = con;
com.CommandText = "SELECT * FROM dbo.Table_1 WHERE ID = #ID;";
com.Parameters.AddWithValue("#ID", textBox1.Text);
com.Parameters.AddWithValue("#RegistrationNumber", textBox1.Text);
com.Parameters.AddWithValue("#StudentName", textBox2.Text);
com.Parameters.AddWithValue("#DateOfBirth", dateTimePicker1.Text);
com.Parameters.AddWithValue("#Age", textBox3.Text);
com.Parameters.AddWithValue("#Gender", Gender);
com.Parameters.AddWithValue("#ContactNumber", textBox4.Text);
com.ExecuteNonQuery();
com.ExecuteReader();
com.Dispose();
}
catch
{
MessageBox.Show("Error");
}
finally
{
con.Close();
}
private void button6_Click(object sender, EventArgs e)
{
string ID = textBox1.Text;
if (ID == null) ;
if (textBox1.Text=="" || textBox2.Text=="" || textBox3.Text=="" || textBox4.Text=="")
{
MessageBox.Show("Please Enter Missing Details");
}
else
{
MessageBox.Show("Record Updated Successfully!!");
string constr = (ConfigurationManager.ConnectionStrings["dbo.Table_1"] != null) ? ConfigurationManager.ConnectionStrings["dbo.Table_1"].ConnectionString : "";
using (SqlConnection con = new SqlConnection(constr))
con.ConnectionString = constr;
if(con.State==ConnectionState.Closed)
{
con.Open();
}
String sql = "SELECT COUNT(*) AS [Count] FROM dbo.Table_1 WHERE ID =#ID";
SqlCommand cmd = new SqlCommand(sql, con) ;
cmd.Parameters.AddWithValue("#ID", ID);
int Id;
if (!int.TryParse(textBox1.Text, out Id))
{
// Report problem to your user
return;
}
SqlDataReader sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (sdr.Read())
{
if (Convert.ToInt32(sdr["count"]) == 1)
{
button2.Enabled = false;
button1.Enabled = true;
}
else
{
button2.Enabled = true;
button1.Enabled = false;
}
}
{
}
}
con.Close();
}
Based on my test, I find that you defined the SqlCommand.CommandText two times.
Please try to modify your code to the following.
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "insert into Student(ID,StudentName,DateOfBirth)values(#ID,#StudentName,#DateOfBirth)";
command.Parameters.AddWithValue("#ID", Convert.ToInt32(ID));
command.Parameters.AddWithValue("#StudentName", textBox2.Text);
command.Parameters.AddWithValue("#DateOfBirth", DateOfBirth
);
Also, please note that we should place the MessageBox.Show after the code com.ExecuteNonQuery();.
Here is a code example you could refer to, based on my test, it works well.
private void button1_Click(object sender, EventArgs e)
{
try
{
string ID = textBox1.Text;
string StudentName = textBox2.Text;
DateTime DateOfBirth = dateTimePicker1.Value;
string constr = "sttr";
SqlConnection connection = new SqlConnection(constr);
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "insert into Student(ID,StudentName,DateOfBirth)values(#ID,#StudentName,#DateOfBirth)";
command.Parameters.AddWithValue("#ID", Convert.ToInt32(ID));
command.Parameters.AddWithValue("#StudentName", textBox2.Text);
command.Parameters.AddWithValue("#DateOfBirth", DateOfBirth);
command.ExecuteNonQuery();
MessageBox.Show("success inserted");
connection.Close();
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
string ID = textBox1.Text;
string constr = "str";
SqlConnection connection = new SqlConnection(constr);
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "SELECT COUNT(*) AS [Count] FROM Student WHERE ID =#ID";
command.Parameters.AddWithValue("#ID", Convert.ToInt32(ID));
SqlDataReader sdr = command.ExecuteReader(CommandBehavior.CloseConnection);
while (sdr.Read())
{
if (Convert.ToInt32(sdr["count"]) == 1)
{
button2.Enabled = false;
button1.Enabled = true;
}
else
{
button2.Enabled = true;
button1.Enabled = false;
}
}
MessageBox.Show("Record Updated Successfully!!");
}
After the below line
com.connection = con;
add below code
com.executenonquery();

Specified cast is not valid in C# and MySQL

How can I fix this ? I try to stop duplication in my attendance but I can't solve this. I try to cast from date.
if(label1.Text != "" && label2.Text != "" && label3.Text != "")
{
try
{
string c = #"(select count(*)from Attendance where Date='"+label1.Text+"')";
MySqlCommand cmd = new MySqlCommand("INSERT INTO Attendance (Name,Date,empIn)VALUES(#Name,#Date,#empIn)", con);
con.Open();
MySqlCommand cmdc = new MySqlCommand(c,con);
int count = (int)cmdc.ExecuteScalar();
if(count > 0)
{
MessageBox.Show("This data is already IN");
}
else
{
cmd.Parameters.Add("#Name", MySqlDbType.VarChar).Value = label3.Text;
cmd.Parameters.Add("#Date", MySqlDbType.VarChar).Value = label1.Text;
cmd.Parameters.Add("#empIn", MySqlDbType.VarChar).Value = label2.Text;
cmd.ExecuteNonQuery();
MessageBox.Show("Attendance Inserted");
}
con.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}
}
It seems that you are looking for insert ignore MySql syntax. Be careful with sql parameters: if query wants DateTime (#Date parameter), provide DateTime (DateTime.ParseExact and alike):
string sql =
#"insert ignore Attendance(
Name,
Date,
empIn)
values(
#Name,
#Date,
#empIn)";
//DONE: wrap IDisposable into using
using (MySqlCommand cmd = new MySqlCommand(sql, con)) {
cmd.Parameters.Add("#Name", MySqlDbType.VarChar).Value = label3.Text;
// If Date is DateTime, provide DateTime, not string
//TODO: provide the right date time format here
cmd.Parameters.Add("#Date", MySqlDbType.DateTime).Value =
DateTime.ParseExact(label1.Text, "d/M/yyyy", CultureInfo.InvariantCulture);
cmd.Parameters.Add("#empIn", MySqlDbType.VarChar).Value = label2.Text;
if (cmd.ExecuteNonQuery() > 0)
MessageBox.Show("Attendance Inserted");
else
MessageBox.Show("This data is already IN");
}

Incorrect syntax near 'achternaam'

I am trying to insert a new row into a SQL Server table from a Winforms application. As far as I know my query is correct but Visual Studio keeps returning an error:
Incorrect syntax near 'achternaam'
I hope that someone can point me in the right direction.
public void UpdateGegevens(int id, string voornaam, string achternaam, string functie, DateTime geboortedatum, decimal uurloon)
{
if (ReturnFirstTime(id) == true)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = con;
command.CommandType = CommandType.Text;
command.CommandText = "INSERT INTO tbl_Gegevens (Id, voornaam, achternaam, geboortedatum, functie, uurloon) VALUES (#Id, #vn, #an, #gb, #f, #ul);";
command.Parameters.Add("#Id", SqlDbType.Int).Value = id;
command.Parameters.Add("#vn", SqlDbType.VarChar).Value = voornaam;
command.Parameters.Add("#an", SqlDbType.VarChar).Value = achternaam;
command.Parameters.Add("#f", SqlDbType.VarChar).Value = functie;
command.Parameters.Add("#gb", SqlDbType.Date).Value = geboortedatum;
command.Parameters.Add("#ul", SqlDbType.Money).Value = uurloon;
try
{
con.Open();
command.ExecuteScalar();
}
catch (SqlException ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
}
}
else
{
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = con;
command.CommandType = CommandType.Text;
command.CommandText = "UPDATE tbl_Gegevens SET voornaam=#vn achternaam=#an geboortedatum=#gb funtie=#f uurloon=#ul WHERE Id = #Id;";
command.Parameters.AddWithValue("#Id", id);
command.Parameters.AddWithValue("#vn", voornaam);
command.Parameters.AddWithValue("#an", achternaam);
command.Parameters.AddWithValue("#gb", geboortedatum);
command.Parameters.AddWithValue("#f", functie);
command.Parameters.AddWithValue("#ul", uurloon);
try
{
con.Open();
command.ExecuteNonQuery();
}
catch (SqlException ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
}
}
}
Here is a specification of tbl_Gegevens:
create table [dbo].[tbl_Gegevens] (
[Id] int not null
, [voornaam] nvarchar(50) null
, [achternaam] nvarchar(50) null
, [geboortedatum] date null
, [functie] nvarchar(50) null
, [uurloon] smallmoney null
, primary key clustered ([Id] asc)
);
I think my dbms is ADO.Net.
This is the way i'm passing the info to the method:
private void btnConfirm_Click(object sender, EventArgs e)
{
if (tbName.Text != "" && tbSurname.Text != "" && tbFunction.Text
!= "" && dtpBirthdate.Value != date && nudSalary.Value != 0)
{
Database1.SetFirstTime(ID);
Database1.UpdateGegevens(ID, tbName.Text, tbSurname.Text, tbFunction.Text, dtpBirthdate.Value, nudSalary.Value);
this.Hide();
frmMain fm = new frmMain(ID);
fm.Show();
}
else
{
MessageBox.Show("Vul alle velden in!");
}
}
This is the query i use to get my id:
public int ReturnLoginID(string username, string password)
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("Select * from tbl_Login where UserName=#username and Password=#password", con);
cmd.Parameters.AddWithValue("#username", username);
cmd.Parameters.AddWithValue("#password", password);
int ID = 9999;
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
reader.Read();
ID = reader.GetInt32(0);
}
con.Close();
return ID;
}
In the UPDATE part of your code there are no commas to separate the fields in the SET list
command.CommandText = #"UPDATE tbl_Gegevens SET voornaam=#vn,
achternaam=#an, geboortedatum=#gb,
funtie=#f, uurloon=#ul WHERE Id = #Id;";
I think that this question could be used to underline the importance of using a debugger. This problem would be solved much sooner if you had stepped through your code using the debugger.

Syntax error in INSERT STATEMENT from c# to Access DB

con.Open();
cmd = new OleDbCommand("insert into login (user, password) values ('" +textBox1 .Text + "','" + textBox2 .Text + "');",con);
cmd.CommandType = CommandType.Text;
int temp = cmd.ExecuteNonQuery();
if (temp > 0)
{
textBox1.Text = null;
textBox2.Text = null;
MessageBox.Show("Record Successfuly Added");
}
else
{
MessageBox.Show("Record Fail to Added");
}
con.Close();
when i try to insert some of error appear ( syntax error in INSERT STATEMENT )
i'm try different method to values like Parameters or direct
plz !
Escape reserved keyword user
use parameterized query
avoid sql injection
Make use of disposable objects
Try this approach:
using (OleDbConnection con = new OleDbConnection(connectionString))
{
con.Open();
using (var cmd = new SqlCommand(
"insert into login ([user], [password]) values (#user, #pass);",
con))
{
cmd.Parameters.Add(new OleDbParameter("#user", textBox1.Text ));
cmd.Parameters.Add(new OleDbParameter("#pass", textBox1.Text ));
if (temp > 0)
{
textBox1.Text = String.Empty;
textBox2.Text = String.Empty;
MessageBox.Show("Record Successfuly Added");
}
else
{
MessageBox.Show("Record Fail to Added");
}
}
}

Categories

Resources