Delete command not working - c#

I want to ask that what is wrong with that code. I am running this and nothing is changed to the data source.
DataRow[] dr = this.U_dt.Select("UserName='"+user+"'");
DataRow dr1 = dr[0];
//U_ad is a dataadapter
//U_dt is a datatable. U_ad.fill(U_dt);
this.U_dt.Rows.Remove(dr1);
U_ad.DeleteCommand = new SqlCommand("Delete from [Users] where [UserName]=#User", con);
U_ad.DeleteCommand.Parameters.Add("#User", SqlDbType.NChar, 20, "[UserName]");
this.U_ad.Update(U_dt);

You try to pass, as value for the parameter #User a string "[UserName]".
This is not the value of a variable containing the user name to search for deletion, but a literal string.
Of course nothing is found in the column UserName with a literal value "[UserName]"
Try instead to use the variable user that you have applied in the Select before
SqlCommand cmd = new SqlCommand("Delete from [Users] where [UserName]=#User", con);
cmd.Parameters.Add("#User", SqlDbType.NChar, 20, user);
cmd.ExecuteNonQuery();
I have used directly the SqlCommand ExecuteNonQuery method, but this should work also using the DeleteCommand of a SqlDataAdapter

can you put your code in try catch like
try{
SqlCommand cmd = new SqlCommand("Delete from [Users] where [UserName]=#User", con);
cmd.Parameters.Add("#User", SqlDbType.NChar, 20, user);
cmd.ExecuteNonQuery();
}catch(Exception ex)
{
System.Console.WriteLine( " ERROR:" + ex.Message );
}
Also there maybe some foreign key which might cause you not to delete the entry. Its always wise to put these sql queries in try catch for safety.
This might help ADO.net simple project

i think the problem is that you remove the row you want to delete from your datatable before calling update ... the update command iterates the rows in your datatable and executes your delete command for all rows with rowstate == Deleted ... but your row has been removed from your datatable so the delete command wont get executed at all.
possible solutions would be to just execute U_ad.DeleteCommand.ExecuteNonQuery() (after settings the #User parameter) and not call DataAdapter.Update at all or to execute dr1.Delete() instead of this.U_dt.Rows.Remove(dr1) and call DataAdapter.Update

Related

Get the recent ID and insert it to another table in ASP.NET

Please help - I'm creating a simple register from I'm trying to get the userID and insert the UserID from User table into the Employee table. I get an error at the line
newID = (int)cmd.ExecuteScalar();
My User table has a primary key UserID, the Employee table has a column UserID as foreign key.
Thank you in advance!
Here is my register.cs
// instantiate
using (SqlConnection con = new SqlConnection(Helper.GetCon()))
{
int newID;
string query = #"INSERT INTO Users VALUES (#TypeID, #EmployeeId, #Username, #Password, #SecurityQuestion1, #SecurityAnswer1, #SecurityQuestion2, #SecurityAnswer2, #DateModified);SELECT CAST(scope_identity() AS int";
con.Open();
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#TypeID", ddlUserTypes.SelectedValue);
cmd.Parameters.AddWithValue("#Username", txtUsername.Text);
cmd.Parameters.AddWithValue("#Password", Helper.CreateSHAHash(txtPW.Text));
cmd.Parameters.AddWithValue("#SecurityQuestion1", ddlSec1.SelectedValue);
cmd.Parameters.AddWithValue("#SecurityAnswer1", txtSecAns1.Text);
cmd.Parameters.AddWithValue("#SecurityQuestion2", ddlSec2.SelectedValue);
cmd.Parameters.AddWithValue("#SecurityAnswer2", txtSecAns2.Text);
cmd.Parameters.AddWithValue("#DateModified", DateTime.Now);
cmd.ExecuteNonQuery();
newID = (int)cmd.ExecuteScalar();
con.Close();
}
string query2 = #"INSERT INTO Employees VALUES (#FirstName, #MiddleName, #LastName, #EmployeeNumber, #Gender, #Birthdate, #Birthplace, #Nationality, #CivilStatus, #PermamentAddress, #PresentAddress, #ContactNumber, #Email, #Position, #Department, #Designation, #DateHired, #EmploymentStatus, #TIN, #SSS, #HDMF, #PHIC, #Supervisor, #Remarks, #Photo, #Attachments, #DateModified)";
using (SqlCommand cmd = new SqlCommand(query2, con))
{
cmd.Parameters.AddWithValue("#FirstName", txtFN.Text);
cmd.Parameters.AddWithValue("#MiddleName", txtMD.Text);
cmd.Parameters.AddWithValue("#LastName", txtLN.Text);
cmd.Parameters.AddWithValue("#EmployeeNumber", txtEmpNo.Text);
cmd.Parameters.AddWithValue("#Gender", ddlGender.SelectedValue);
cmd.Parameters.AddWithValue("#Birthdate", txtbdate.Text);
cmd.Parameters.AddWithValue("#Birthplace", txtBP.Text);
cmd.Parameters.AddWithValue("#Nationality", txtNat.Text);
cmd.Parameters.AddWithValue("#CivilStatus", ddlCIv.SelectedValue);
cmd.Parameters.AddWithValue("#PermamentAddress", txtPermAdd.Text);
cmd.Parameters.AddWithValue("#PresentAddress", txtPreAdd.Text);
cmd.Parameters.AddWithValue("#ContactNumber", txtContactNo.Text);
cmd.Parameters.AddWithValue("#Email", txtEmail.Text);
cmd.Parameters.AddWithValue("#Position", txtPosi.Text);
cmd.Parameters.AddWithValue("#Department", txtDept.Text);
cmd.Parameters.AddWithValue("#Designation", txtDesig.Text);
cmd.Parameters.AddWithValue("#DateHired", txtdateh.Text);
cmd.Parameters.AddWithValue("#EmploymentStatus", txtEmpl.Text);
cmd.Parameters.AddWithValue("#TIN", txtTin.Text);
cmd.Parameters.AddWithValue("#SSS", txtSSS.Text);
cmd.Parameters.AddWithValue("#HDMF", txtPhilH.Text);
cmd.Parameters.AddWithValue("#PHIC", txtPag.Text);
cmd.Parameters.AddWithValue("#Supervisor", txtSuper.Text);
cmd.Parameters.AddWithValue("#Remarks", txtRemarks.Text);
string fileName = DateTime.Now.ToString("yyyyMMddHHmmss-") + fuImage.FileName;
cmd.Parameters.AddWithValue("#Photo", fileName);
fuImage.SaveAs(Server.MapPath("~/EmployeeData/Images/" + fileName));
string attachments = DateTime.Now.ToString("yyyyMMddHHmmss-") + fuAttach.FileName;
cmd.Parameters.AddWithValue("#Attachments", attachments);
fuAttach.SaveAs(Server.MapPath("~/EmployeeData/Attachments/" + attachments));
cmd.Parameters.AddWithValue("#DateModified", DateTime.Now);
cmd.ExecuteNonQuery();
con.Close();
}
}
I'm not sure how this code gets an error at the line you're saying it happens, since I'd expect an error.at the line before the one mentioned. Here are a variety of tips, too long for a comment. I hope they sort out the problem, and if they dont, then the first point will help you get to the answer.
When asking for help about an error, please post the error that you got. This is the most important thing about diagnosing an error.
The line before the error is cmd.ExecuteNonQuery(), which will execute the command, inserting the record. Then you do cmd.ExecuteScalar(), which will execute the command again, inserting another record. Remove the cmd.ExecuteNonQuery(), since you need the identity value back from ExecuteScalar.
I'm not sure how the cmd.ExecuteNonQuery() works (it must do, unless you are mistaken in telling us that it crashes on the next line), since there is a typo in the query, missing the close bracket from the end SELECT CAST(scope_identity() AS int.
Please Can we stop using AddWithValue.
There's no need to Close the connection (ever), since it's in a using block. When it exits that block, the implicit Dispose will call Close.
Consider adding a Transaction. You are doing two separate inserts. If the second one fails, you will be left with the first record in the database. If you use a transaction around both commands, then either they both get in, or neither get in.
You're passing #DateModified the value DateTime.Now, which is a 'Local' time (look at the Kind property). When you read the value back from SQL, unless you call SpecifyKind, it won't be a local time, leading to discrepancies. Safer to always store and read the value as UTC (by using DateTime.UtcNow here, and SpecifyKind UTC when you read it) or switch to using DateTimeOffset.

Cannot insert value via SqlDataAdapter

I am learning how to work with SQL in C#, and I got in troubles with using SqlDataAdapter. I have tried to use direct queries via SqlCommand class and everything works fine, but when I rewrote my code to use SqlDataAdapter I have no changes in my table. There is my code:
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ADO"]
.ConnectionString);
connection.Open();
SqlDataAdapter daUser = new SqlDataAdapter("SELECT * FROM Books", connection);
SqlCommand insert = new SqlCommand();
insert.Connection = connection;
insert.CommandText = "INSERT INTO Books (name, author) VALUES (#name, #author);";
SqlParameterCollection pc = insert.Parameters;
pc.Add("#name", SqlDbType.VarChar, 20, "test123");
pc.Add("#author", SqlDbType.VarChar, 20, "test322");
daUser.InsertCommand = insert;
DataSet ds = new DataSet();
daUser.Fill(ds, "Books");
daUser.Update(ds, "Books");
Table Books was created with this SQL query in SQL Server Management Studio:
CREATE TABLE Books
(
id int PRIMARY KEY IDENTITY(1,1),
name varchar(MAX) NOT NULL,
author varchar(MAX) NOT NULL
)
INSERT INTO Books(name, author)
VALUES('1984', 'George Orwell'), ('Fathers and sons', 'Dostoevski')
Looks like I am missing something to do, that why my code have no effect on table.
SqlDataAdapter.Update will call its InsertCommand only for the rows of datatable having RowState = DataRowState.Added.
This rowstate is automatically assigned to the datarows being added to rows collection using DataTable.Add method (until next call to AcceptChanges method). Also you can use DataRow.SetAdded method to force this state assignment.
Since you're not modifying/adding anything in you datatable after you've populated it with select command, it has nothing to insert.
Change your code to something like
daUser.Fill(ds, "Books");
var newBook = daUser.Tables[0].NewRow();
newBook["name"] = "New Book";
newBook["author"] = "Author Name";
daUser.Tables[0].Rows.Add(newBook);
daUser.Update(ds, "Books");
and in this case it should be new row added to the database table.
See MSDN for reference.
Just to clarify the previous answer, which is correct, you want to call ExecuteNonQuery() on the command not the dataAdapter.
SqlCommand insert = new SqlCommand();
insert.Connection = connection;
insert.CommandText = "INSERT INTO Books (name, author) VALUES (#name,
#author);";
SqlParameterCollection pc = insert.Parameters;
pc.Add("#name", SqlDbType.VarChar, 20, "test123");
pc.Add("#author",
SqlDbType.VarChar, 20, "test322");
// you do not need this line if you execute the insert on the command object.
// daUser.InsertCommand = insert;
//Add this line instead:
insert.ExecuteNonQuery();
Joey

Updating the sql server database in urdu(language) text

I am simply making a windows form in c# where I can insert, update and delete the data.
I want to insert data in URDU text. I am done with inserting data with following code :
SqlCommand cmd = new SqlCommand("insert into tblTeams values (#ID, #SchoolName, #TeamName)", con);
cmd.Parameters.AddWithValue("#ID", txtBoxID.Text);
cmd.Parameters.AddWithValue("#SchoolName", txtBoxSName.Text);
cmd.Parameters.AddWithValue("#TeamName", txtBoxTName.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
But when trying to update data not getting any clue how to do it...
SqlDataAdapter sda = new SqlDataAdapter("update tblTeams set SchoolName='"+txtBoxSName.Text+"',TeamName='"+txtBoxTName.Text+"'where ID='"+txtBoxID.Text+"' ", con);
con.Open();
sda.SelectCommand.ExecuteNonQuery();
con.Close();
Above piece of code updates the database but not in URDU, in database only "?????" shows...
In SQL server all the insert, update and delete works but I want to do it in front end...
Form design is also attached...enter image description here
Thanks in advance!
Done with updation also and thanks for your support...
Here is the code:
SqlCommand cmd = new SqlCommand("update tblTeams set SchoolName=#SchoolName, TeamName=#TeamName where ID=#ID ", con);
cmd.Parameters.AddWithValue("#ID", txtBoxID.Text);
cmd.Parameters.AddWithValue("#SchoolName", txtBoxSName.Text);
cmd.Parameters.AddWithValue("#TeamName", txtBoxTName.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
This is most likely happening because your columns don't support Unicode. You'll need to use nvarchar, or nchar in your columns.
Alternatively, your TextBox doesn't support unicode text. Try a different font, like Arial.
Don't use the update code without Parameters. It's vulnerable to SQL injection attacks. Instead, use parameters in both, like you did in the first.
Finally, you can prefix the insert values with N'urdutexthere', like this:
SqlCommand cmd = new SqlCommand("UPDATE tblTeams SET SchoolName=N'#SchoolName',TeamName=N'#TeamName' WHERE ID='#ID'", con);
cmd.Parameters.AddWithValue("#ID", txtBoxID.Text);
cmd.Parameters.AddWithValue("#SchoolName", txtBoxSName.Text);
cmd.Parameters.AddWithValue("#TeamName", txtBoxTName.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();

Insert a value in a table from another table using a variable in C# , SQL Server

I have to insert some values in a table while fetching them from another table. Here is my code:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString);
SqlCommand myCommand = new SqlCommand("SELECT Name FROM TableName WHERE Id = '" + Id + "'", con);
SqlDataReader rdr = myCommand.ExecuteReader();
if (dr.HasRows)
{
while (rdr.Read())
{
// User exist - get email
string Name = rdr["Name"].ToString();
}
}
My question is how to insert the name into another table.
I do not want to use a textbox for this the value must be inserted as a variable into other table. I use following script to insert data . but error message is Id not found. Please let me know if I am missing something
SqlCommand cmd = new SqlCommand(#"insert into finalTable (AccountNumber) VALUES (#string)", con);
I use following script to insert data . but error message is Id not found.
SqlCommand cmd = new SqlCommand(#"insert into finalTable (AccountNumber) VALUES
(#string)", con);
You need to specify a value for all columns in the table, unless some columns have default values. Its hard to tell without the exact error message, but it sounds like Id is probably the primary key column and not set to auto increment, so you must supply a value for Id. Since you are inserting, it must be a value not yet used in the table. Depending on your needs, you might want to change finalTable's ID to be auto increment.
On a side note, you are not disposing of things (like your DB connection) that implement IDisposable. The using keyword is your friend here.

Update only one column using ID in asp.net

I want to update only one column in my table by ID .
I don't have any error but this don't work, it won't update. I have ID column and 7 more columns.
SqlCommand cmd1 = new SqlCommand("update table set amount=#kol where ID=#id" , con);
cmd1.Parameters.AddWithValue("#id", textbox1.Text);
cmd1.Parameters.AddWithValue("#kol", textbox2.Text );
Is your table named "table" or is that just for the example here?
Because otherwise you properbly need to change "table" to whatever table your're trying to update. or surround it with [] if it is actually called "table"
Can you please check that you have commited your work , if there is no exception then that will be the reason
and if not put setautocommit(true) - java version
you can find it for c#
please check whether table name is correct and the table which you are verifying is correct
please give some other table name than table for good practice
As long as you have con.Open and ExecuteNonQuery and have the username/password and connectionstring right your code will work.
This will work after you change the connectionstring, if not the problem is sql server.
private void UpdateTable()
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=YourDataBase;Persist Security Info=True;User ID=username;Password=pass");
SqlCommand cmd1 = new SqlCommand("update YourTable set amount=#kol where ID=#id", con);
cmd1.Parameters.AddWithValue("#id", textBox1.Text);
cmd1.Parameters.AddWithValue("#kol", textBox2.Text);
con.Open();
cmd1.ExecuteNonQuery();
}

Categories