Delete Command C# + SQL Server - c#

I'm performing a command to erase data from a DataGridView
But I can not make it work, I just want to select a line and erase it
In addition to programming a button that says "Delete" so that when you click on it, the selected data in the DataGridView will be deleted
I need really help
I am lost
My Table is "Person"
My Column is "ID"
Instances
{SqlConnection cn;
SqlCommand cmd;
SqlDataReader dr;
SqlDataAdapter da;
DataTable dt;}
public string Del(int ID)
{
string ouk = "Delete Work";
try
{
cmd = new SqlCommand("Delete From Person Where = ID )", cn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
ouk = "Bad character:" + ex.ToString();
}
return ouk;
}
For Button Erase at DataGridView
private void buttondel_Click(object sender, EventArgs e)
{
MessageBox.Show(c.Del(TBID));
}

The issue is that your SQL query is malformed and that you're not passing the ID to the query:
"Delete From Person Where = ID )"
One side of the equality check is missing, and you have an unexpected closing bracket.
You should change your query to accept a parameter:
"Delete From Person Where ID = #id"
and then pass the parameter to your command:
cmd.Parameters.Add("#id", SqlDbType.Int).Value = ID;
So it becomes:
try
{
using (cmd = new SqlCommand("Delete From Person Where ID = #id", cn))
{
cmd.Parameters.Add("#id", SqlDbType.Int).Value = ID;
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
ouk = "Bad character:" + ex.ToString();
}
I've taken the liberty of wrapping SqlCommand in a using statement so that it's disposed once we're done with it.

Related

How to read data from a mysql table in c#?

When I start the program I always get this error: could not find specified column in results:firstname.
I changed "firstname" for any other column and it is giving me the same error. I have tested the connection also and the connection is properly written.
public partial class frmDashboard : Form
{
public frmDashboard()
{
InitializeComponent();
}
public frmDashboard(string user)
{
InitializeComponent();
MySqlConnection connect = new MySqlConnection("Server=localhost;Database=mydb;user=root;Pwd=carolle;SslMode=none");
MySqlCommand cmd = new MySqlCommand("select upper(customer.firstname) from mydb.customer where customer.email = '" + user + "';");
cmd.CommandType = CommandType.Text;
cmd.Connection = connect;
connect.Open();
try
{
MySqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
lblusername.Text = dr.GetString("firstname");
}
dr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
thank you in advance.
That's due to your use of upper which changes the result set.
Using an alias with AS can fix this.
SELECT upper(customer.firstname) AS firstname FROM mydb.customer WHERE customer.email = '"+ user + "';"
Also you should be using parameters, not string concatenation, when creating queries for a wide variety of reasons including security and type safety.
If you prefer you can retrieve columns using indexes instead, changing
dr.GetString("firstname");
to
dr.GetString(0);
The column index corresponds to the ordering of columns in the SELECT statement.

Delete a record from database

I'm trying to delete record from data base MSSQL by entering the ID and hit delete btn. i didn't get any error and it give recorded deleted successful but once i check database i see the record doesn't deleted
protected void btnDelete_Click(object sender, EventArgs e)
{
try
{
if (txtImgID.Text == "")
{
Response.Write("Enter Image Id To Delete");
}
else
{
SqlCommand cmd = new SqlCommand();
SqlConnection con = new SqlConnection();
con = new SqlConnection(ConfigurationManager.ConnectionStrings["GMSConnectionString"].ConnectionString);
con.Open();
cmd = new SqlCommand("delete from certf where id=" + txtImgID.Text + "", con);
lblsubmitt.Text = "Data Deleted Sucessfully";
}
}
catch (Exception)
{
lblsubmitt.Text = "You haven't Submited any data";
}
}
var idToDelete = int.Parse(txtImgID.Text); // this is not necessary if the data type in the DB is actually a string
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["GMSConnectionString"].ConnectionString))
using (SqlCommand cmd = new SqlCommand("DELETE FROM [certf] WHERE id = #id", con))
{
// I am assuming that id is an integer but if it is a varchar/string then use the line below this one
// cmd.Parameters.Add("#id", SqlDbType.VarChar, 100).Value = txtImgID.Text;
cmd.Parameters.Add("#id", SqlDbType.Int32).Value = idToDelete;
cmd.ExecuteNonQuery();
}
You need to call ExecuteNonQuery which executes the query against the database.
Always use parameters instead of string concatenation in your queries. It guards against sql injection and ensures you never has issues with strings that contain escape characters.
I did not include any error handling or return messages but do note that you are throwing away all the good stuff in your excetion handler's catch block, you will never know why a query failed after this has executed.

I need to update my database values using c#. But there is an error message when running. What can be the reason?

I have four text box values called txtName, txtId, txtAdd, txtTel. I need to update an existing record in my database table. But the code is not working. Can someone help me to identify my errors. Here is my code.
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\User\documents\visual studio 2012\Projects\WindowsFormsApplication1\WindowsFormsApplication1\Database4.mdf;Integrated Security=True");
try
{
String name = txtName.Text;
String id = txtId.Text;
String address = txtAdd.Text;
String tel = txtTel.Text;
String SqlQuery = "UPDATE [Table]VALUES (#id,#name,#tel,#address)";
SqlCommand cmnd = new SqlCommand(SqlQuery, con);
con.Open();
cmnd.ExecuteNonQuery();
MessageBox.Show("Saved Successfully");
}
catch (Exception ex)
{
MessageBox.Show("Error occured while saving" + ex);
}
finally
{
con.Close();
}
Plese help me
Your update Syntax is wrong. Also add the parameters to your command:
SQL UPDATE Syntax:
UPDATE table_name SET column1=value1,column2=value2,...
WHERE some_column=some_value;
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\User\documents\visual studio 2012\Projects\WindowsFormsApplication1\WindowsFormsApplication1\Database4.mdf;Integrated Security=True");
try
{
String name = txtName.Text;
String id = txtId.Text;
String address = txtAdd.Text;
String tel = txtTel.Text;
String SqlQuery = "UPDATE [Table] SET name = #name, tel = #tel, [address] = #address where [id] = #id";
SqlCommand cmnd = new SqlCommand(SqlQuery, con);
cmnd.Parameters.AddWithValue("#id", id);
cmnd.Parameters.AddWithValue("#name", name);
cmnd.Parameters.AddWithValue("#tel", tel);
cmnd.Parameters.AddWithValue("#address", address);
con.Open();
cmnd.ExecuteNonQuery();
MessageBox.Show("Saved Successfully");
}
catch (Exception ex)
{
MessageBox.Show("Error occured while saving" + ex);
}
finally
{
con.Close();
}
Your update query is wrong. Please see some examples.
After assigning your TextBox values to some strings, make sure that you use them after that.
You don't need to write (in your case) finally{} block manually, use using() statement instead of that.
Put your SqlCommand into using().
Use parameterized queries
Try this:
try
{
using(SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\User\documents\visual studio 2012\Projects\WindowsFormsApplication1\WindowsFormsApplication1\Database4.mdf;Integrated Security=True"))
{
con.Open();
using(SqlCommand cmnd = con.CreateCommand())
{
// Your update query must look like something like this
cmnd.CommandText = #"UPDATE [Table]
SET Name = #name,
Tel = #tel,
Address = #address
WHERE Id = #id";
cmd.Parameters.Add(new SqlParameter("#id", txtId.Text));
cmd.Parameters.Add(new SqlParameter("#name", txtName.Text));
cmd.Parameters.Add(new SqlParameter("#tel", txtTel.Text));
cmd.Parameters.Add(new SqlParameter("#address", txtAdd.Text));
cmnd.ExecuteNonQuery();
MessageBox.Show("Saved Successfully");
}
}
}
catch(Exception ex)
{
//Handle your exception here
}
I guess you could try adding these lines of code to add parameters:
cmnd.Parameters.Add(new SqlParameter("#id", id);
cmnd.Parameters.Add(new SqlParameter("#name", name);
cmnd.Parameters.Add(new SqlParameter("#tel", tel);
cmnd.Parameters.Add(new SqlParameter("#address", address);

Database not storing information properly, stores info on different rows

The database is not storing information all on the same row. On the first page, when I click the button it records it and that's fine, it's stored. Then on the next page, when i click the button, it stores the information, but on a different row? Any solutions? Heres the problem, and code below.
PAGE 1
public void addInformationToDatabase()
{
string Sex = ddlGender.Text;
string Name = tbxName.Text;
string DOB = tbxDOB.Text;
string connectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection Con = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand();
command.Connection = Con;
command.CommandType = CommandType.Text;
command.CommandText = "INSERT INTO [User] (GenderID,Name,DOB) VALUES(#Sex,#Name,#DOB)";
command.Parameters.AddWithValue("#Sex", Sex);
command.Parameters.AddWithValue("#Name", Name);
command.Parameters.AddWithValue("#DOB", DOB);
try
{
Con.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
Con.Close();
}
}
2ND PAGE
public void save()
{
string checkboxSelection = CheckBoxList1.SelectedItem.ToString();
string connectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection Con = new SqlConnection(connectionString);
SqlCommand c = new SqlCommand();
c.Connection = Con;
c.CommandType = CommandType.Text;
c.CommandText = "INSERT INTO [User] (Ans1) VALUES(#Ans1)";
c.Parameters.AddWithValue("#Ans1", checkboxSelection);
try
{
Con.Open();
c.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
Con.Close();
}
}
Any help appreciated
your first page needs to get the ID back following the insert and then your second page needs to do an update based on that ID, not a subsequent insert.
There are a lot of resources about getting ids back - e.g How to get last inserted id?
(I'm assuming the id field uniquely identifies your row)
first query -
c.CommandText = "INSERT INTO [User] (Ans1) VALUES(#Ans1); SELECT SCOPE_IDENTITY()";
...
int userID = (Int32) c.ExecuteScalar();
you'll need to pass that ID to your 2nd page and change the insert to be an update:
"UPDATE User] SET Ans1 = #Ans1 WHERE Id = #id";
you'll also need to add the id as a parameter
c.Parameters.AddWithValue("#id", userID);

SqlDataReader into List<> - Quickest way

When I am reading data from a sql db and want to add all the items into a list (ie. eonumlist) below. Do I need to specifically assign each field or can I mass assign this data? I'm doing this for a report and want to get the data quickly. Maybe I should use a dataset instead. I have 40+ fields to bring into the report and want to do this quickly. Looking for suggestions.
public static List<EngOrd> GetDistinctEONum()
{
List<EngOrd> eonumlist = new List<EngOrd>();
SqlConnection cnn = SqlDB.GetConnection();
string strsql = "select distinct eonum " +
"from engord " +
"union " +
"select 'zALL' as eonum " +
"order by eonum desc";
SqlCommand cmd = new SqlCommand(strsql, cnn);
try
{
cnn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
EngOrd engord = new EngOrd();
engord.EONum = reader["eonum"].ToString();
engord.Name = reader["name"].ToString();
engord.Address = reader["address"].ToString();
eonumlist.Add(engord);
}
reader.Close();
}
catch (SqlException ex)
{
throw ex;
}
finally
{
cnn.Close();
}
return eonumlist;
}
I do something similar storing data from a db into a combo box.
To do this i use the following code.
public static void FillDropDownList(System.Windows.Forms.ComboBox cboMethodName, String myDSN, String myServer)
{
SqlDataReader myReader;
String ConnectionString = "Server="+myServer+"\\sql2008r2;Database="+myDSN+";Trusted_Connection=True;";
using (SqlConnection cn = new SqlConnection(ConnectionString))
{
cn.Open();
try
{
SqlCommand cmd = new SqlCommand("select * from tablename", cn);
using (myReader = cmd.ExecuteReader())
{
while (myReader.Read())
{
cboMethodName.Items.Add(myReader.GetValue(0).ToString());
}
}
}
catch (SqlException e)
{
MessageBox.Show(e.ToString());
return;
}
}
}
This connects to the database and reads each record of the table adding the value in column 0 (Name) to a combo box.
I would think you can do something similar with a list making sure the index values are correct.
Store the data as xml, then deserialize the xml to the list.

Categories