error while updating a database in ASP.NET - c#

I am having trouble updating an SQL database, the problem is not that it doesn't update at all, but that particular parameters are being updated while the others are not.
here is the code for updating the parameters:
string EditRequest = "UPDATE Requests SET Description = #Desc, BJustif = #Justif, Priority = #Priority, Requested_System = #Requested, Request_Status = #Stat WHERE";
EditRequest += " Req_ID=#ID";
SqlConnection Submit_conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["DBConn"].ConnectionString);
SqlCommand Submit_comm = new SqlCommand(EditRequest, Submit_conn);
Submit_comm.Parameters.AddWithValue("#ID", Request.QueryString["reqid"]);
Submit_comm.Parameters.AddWithValue("#Desc", DescBox.Text);
Submit_comm.Parameters.AddWithValue("#Justif", JustifBox.Text);
Submit_comm.Parameters.AddWithValue("#Priority", PriorityList.SelectedValue);
Submit_comm.Parameters.AddWithValue("#Requested", RelatedBox.Text);
Submit_comm.Parameters.AddWithValue("#Stat", 1);
Submit_conn.Open();
Submit_comm.ExecuteNonQuery();
Submit_comm.Dispose();
Submit_comm = null;
Submit_conn.Close();
get_Description();
Page.ClientScript.RegisterStartupScript(this.GetType(), "Refresh", "ReloadPage();", true);
this function is called by a button on a pop-up form which shows the parameters content that is being changed in a text box which is also used to submit the changes back to the database, but when I press submit, the parameters which are displayed on the form don't change, I can't find any problem wit the code, even though I've compared it to similar code which is working fine.
In case you need to, here is one of the text boxes I'm using to display and edit the content:
<asp:TextBox ID="JustifBox" TextMode="MultiLine" runat="server" Width="250" Height="50"></asp:TextBox>
What exactly is wrong with the code?
EDIT: I forgot to mention that when I traced the function, it appeared that the controls' content did not change when I submitted them, but were resubmitted as if they were unchanged in their original form.

You mentioned two problems here:
1) Fields in the database are not updated when the UPDATE is performed
2) The UI is not updated with the latest data
First tackle the SQL UPDATE query. What fields are not being updated? Copy paste the T-SQL query in the query analyzer and then check which field is being updated and which is NOT. Also, your code is OPEN to SQL injections so read about that and then adjust the code.
For the UI not being updated you need to see whether you are even populating the UI fields with the correct object.

Related

Dynamic SQL issue - C# Forms (Datagridview)

I am currently trying to update my DataGridView to my database. I want to be able to update it with the enter key. But I am getting this error:
"Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information."
Here is a picture of the code(as well its below in code snippet)
Some of the code
Here is how the Datagridview is loaded:
private void RampBoardLoader()
{
SqlConnection connection = new SqlConnection(ConnectionLoader.ConnectionString("Threshold"));
connection.Open();
SqlCommand selectRampBoard = new SqlCommand("Select_Ramp_Data", connection);
selectRampBoard.CommandType = CommandType.StoredProcedure;
selectRampBoard.Parameters.AddWithValue("#DateID", dateTimeRamp.Value.Date);
dt = new DataTable();
dataAdapter = new SqlDataAdapter(selectRampBoard);
dset = new DataSet();
dataAdapter.Fill(dset, "Ramp_Board");
dgvRampBoard.DataSource = dset.Tables[0];
connection.Close();
}
Here is where I'm trying to update the datagridview:
private void dgvRampBoard_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.Handled = true;
scb = new SqlCommandBuilder(dataAdapter);
dgvRampBoard.EndEdit();
this.dataAdapter.Update(dset, "Ramp_Board");
}
}
I've been looking around to try to find the answer to this. Every post I see everyone says that you need to make sure your table has a primary key. My table does have a primary key. It has 2 primary keys. "Flight Number" and "DateID". I'm not sure if it's because I have 2 primary keys, if that's why I'm getting this issue.
Attached is image of Database of my stored procedure. You can also see the columns, I have 2 primary keys
Stored Procedure
How to make life easy:
(Note; this only works in a net framework project; the designer has bugs in net core and Microsoft have disabled it. There are tricks you can pull if you want to work in core, but they basically entail using a net framework project to do the editing and a netcore to do the running)
add a dataset type file to your project
open it, right click its surface, choose add tableadapter
Set up your connection
Choose to use stored procedures to get your data
Choose your sprocs (I assume you have one for updating ?)
Name the Fill/GetData methods appropriately (FillByDateId ?)
Save the dataset
Go to a new form
Open DataSources window on View menu, other windows
Drag the node representing your table, onto your form. You should see a grid, binding source, dataset and navigator appear
That's it, you should be able to just run the app now, enter some date Id in the box, hit fill, change the data, hit save..
You can find the code the designer write for you in the normal code behind and in the FormXx.Designer.cs files if you're curious how it works. A tableadaptermanager will call tableadapter.Update(datatable) on "parent, child" order for every table that needs updating. Table adapter's Update uses the InsertCommand, UpdateCommand and DeleteCommand as appropriate to persist each row change according to what the row state is

Database First with Windows Form

Hi I have a windows Form Application and using Database First Approach. When I am trying to save data using following code its not showing any error but not saving data into my .mdf database.
Models.NorthwoodRetreatsDBEntities db = new Models.NorthwoodRetreatsDBEntities();
db.Treatments.Add(new Models.Treatment() {
Name=_name,
address=_address,
phone=_phoneNo,
Email=_emailAddress
});
db.SaveChanges();
Not showing error I am also trying see is it inserted using the following line of code
bool a = db.ChangeTracker.HasChanges(); //double check if there was any change detected by EF or not?
it is returning true and
int UserID = db.Treatments.Max(item => item.AccommodationID);
Always returning 1 but when I explore database table showing nothing there and also when I am adding second item "int UserID" again 1. Now I am just wondering that can I use Database First EF with Windows Form. Could you please advice.

Attempting to run Update Query doesn't update dataset

So I have a Database that I created a Dataset from, I'm attempting to run an Update on it and I cannot get it to update the Dataset (and subsequently the Database) with the result. I built the Query using Visual Studio's query builder and when I run it through there it changes the data in the way that it should. When I run the code I put in a MessageBox to show the number of rows the query changed and it is returning 1 as it should. I'm at a loss as to why it won't 'commit' the update and I'm sure I'm missing something very simple.
Here is the Query I setup (named "UpdateQuery")
UPDATE Bug_Master
SET Name = #Name, Test_App = #Test_App, Bug_Type = #Bug_Type, Bug_Active = #Bug_Active, Bug_Description = #Bug_Description, Bug_Keywords = #Bug_Keywords
WHERE (Id = #Original_Id);
In the Load event for the form I have
this.bug_MasterTableAdapter.Fill(this.bugManagerDataSet.Bug_Master);
And here is where I am calling the Query and trying to update (I know I should use 'using' but I'll pretty up the code after I get this to work so forgive the inelegance)
SqlConnection connection = new SqlConnection(strSQLConnectionString);
connection.Open();
int iResult = bug_MasterTableAdapter.UpdateQuery("Error One 1", "PassVault", "Runtime", "True", "Description Test", "Keywords Test", 1);
MessageBox.Show(iResult.ToString());
bug_MasterTableAdapter.Update(bugManagerDataSet.Bug_Master);
connection.Close();
As I mentioned above the MessageBox shows '1'. Is there a critical step I'm missing on how to do this? It has been a long time since I messed with SQL so I've had to bumble my way back to it and have no doubt I've missed/messed up some things.
Thanks in advance.
erik
Found the solution. Turns out the 'copy to output directory' property on the database file was set to 'always copy'. So when I ran the program it would make changes to the database in the \bin\debug folder while I was looking at the one in the app folder. Then when I would restart the program to check the values in there it would overwrite the changed version of the database in \bin\debug with the unchanged version from the project.
So, the upshot is for anyone else that runs into something similar is set the 'Copy to Output Directory' option on the database to 'Copy if Newer'.
Thanks to all who took a look.
erik

Entity Framework not flushing data to the database

I am using Visual Studio 2012. I have a very simple Products table in a Local Database (cleverly named Database1). It has two fields: id and Name. I preloaded it with a few test data.
The following code should update the Name of the first Product. Internally, it does. I can retrieve all Products and see that the first one's Name is "Shirt." But the change is never flushed to the database. The record is never updated. Examining the database reveals that the name has not been changed.
My question is simple: Why are changes not being sent to the database?
using (var context = new Database1Entities())
{
var products = context.Products;
products.First().Name = "Shirt";
context.SaveChanges();
}
Thanks in advance.
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
EDIT:
I tried my best to enter the full code and output here. But, no matter what I do, I continue to get the "Your post appears to contain code that is not properly formatted" error message. After 30 minutes I am giving up.
EDIT:
The code and output is here: http://pastebin.com/GmQtwAND
I discovered the issue...and its solution.
The "Copy to Output Directory" property of the database file was set to "Copy always." This, of course, meant that every time the application was built, a fresh copy was placed into the Bin directory. The fix was to set it to "Copy if newer." Doh.
In other words, the changes were being persisted in the database, but then the database was being clobbered when the application got rebuilt.
Well this could mean that you're not tracking changes, how about you try to set the State to -> Modified and see if it's going to work:
var product = products.First();
product.Name = "Shirt";
product.State = EntityState.Modified;
context.SaveChanges();
If you want to enable it for the context you can do it like this:
context.Configuration.AutoDetectChangesEnabled = true;

Form view update issues

I am using asp.net with a c# back end to create a job website with a master and detail view.
To pull data I am using entity framework that was reverse engineered code first from a SQL server 2005 instance running on the same xp machine that I am doing development on. I would like the detail view on the website to be able view and edit existing records selected on the master view, but also be able to insert records.
So far I gotten to the point where the detail view can be used both view and insert records but editing has been unsuccessful as of yet. I don't get an error on update, and the I see no change reflected anywhere.
Some of the solutions I've seen say that you have to have DataKeyNames defined. (In my case I have used a field: Job_UID, which is actually how I connected the detail and master views.)
I have tried to made sure that I have the update query defined properly by reducing the number of items in the where clause to just reflect my PK and also by testing the query in the query designer.
Here are my queries:
SelectCommand="SELECT Job_Details.Job_UID, Job_Details.Job_Title, Job_Details.Job_Store_ID, Job_Details.Job_Type_Id, Job_Details.Job_Description, Job_Details.Job_Responsibilities, Job_Details.Job_Pay, Job_Details.Job_Supervisor, Job_Details.Job_Start_Date, Job_Details.Job_End_Date, Job_Details.Job_Meta_Post_StartDate, Job_Details.Job_Meta_Post_EndDate, Job_Details.Job_Meta_Keywords, Store_Look_Up.Store_Name, Store_Look_Up.Store_Region, Store_Look_Up.Store_Address, Job_Type.Job_Type_Name, Job_Type.Job_Type_Description FROM Job_Details INNER JOIN Job_Type ON Job_Details.Job_Type_Id = Job_Type.Job_Type_Id INNER JOIN Store_Look_Up ON Job_Details.Job_Store_ID = Store_Look_Up.Store_Id WHERE (Job_Details.Job_UID = #Job_UID)"
InsertCommand="INSERT INTO Job_Details(Job_UID, Job_Title, Job_Store_ID, Job_Type_Id, Job_Description, Job_Responsibilities, Job_Pay, Job_Supervisor, Job_Start_Date, Job_End_Date, Job_Meta_Post_StartDate, Job_Meta_Post_EndDate, Job_Meta_Keywords) VALUES (#Job_UID, #Job_Title, #Job_Store_ID, #Job_Type_Id, #Job_Description, #Job_Responsibilities, #Job_Pay, #Job_Supervisor, #Job_Start_Date, #Job_End_Date, #Job_Meta_Post_StartDate, #Job_Meta_Post_EndDate, #Job_Meta_Keywords)"
UpdateCommand="UPDATE Job_Details SET Job_Title = #Job_Title, Job_Store_ID = #Job_Store_ID, Job_Type_Id = #Job_Type_Id, Job_Description = #Job_Description, Job_Responsibilities = #Job_Responsibilities, Job_Pay = #Job_Pay, Job_Supervisor = #Job_Supervisor, Job_Start_Date = #Job_Start_Date, Job_End_Date = #Job_End_Date, Job_Meta_Post_StartDate = #Job_Meta_Post_StartDate, Job_Meta_Post_EndDate = #Job_Meta_Post_EndDate, Job_Meta_Keywords = #Job_Meta_Keywords WHERE (Job_UID = #Original__Job_UID)">
The rest of the solutions I've seen seem to involve a lot of custom coding. Shouldn't there be a way to do this just using Visual Studio's code generator, with some coding tweaks?
Any help would be appreciated, and thanks in advance!
The problem was with my update command:
I used the ItemUpdatedEvent of my FormView to determine how many rows were modified: 0 in my case.
string textToDisplay = string.Empty;
textToDisplay += "AffectedRows: " + e.AffectedRows.ToString() + "|";
Label1.Text = textToDisplay;
Once I was clearly able to see how many rows were being updated, I proceeded to test the query. I replaced #Original_Job_UID with the PK. And it worked on the page.
Then I looked through some MSDN documentation and saw that the filter should have been
#Job_UID. I entered it and it worked!
Hope this helps you!

Categories