Can't submit changes to database or page controls - asp.net

I've got a pretty simple page, consisting of two DropDownLists populated from the database, and a button. The purpose of the page is pretty simply to allow users to delete an entry from the database. When the button is clicked then a simple LINQ query is executed to delete the intended target, and remove the entry from the dropdownlists, but it doesn't work unless the response is redirected within that function, even if SubmitChanges() was called. Why would this happen?
Edit: Code
protected void Page_Init(object sender, EventArgs e)
{
var result = Database.DB.Data.GetTable<Database.tbl_module_>().Where(module => module.deptCode == ((User)Session["user"]).deptCode);
foreach (var row in result)
{
this.listModuleCode.Items.Add(new System.Web.UI.WebControls.ListItem(row.code));
this.listModuleTitle.Items.Add(new System.Web.UI.WebControls.ListItem(row.title));
}
}
protected void Delete_Click(object sender, EventArgs e)
{
var DB = Database.DB.Data;
var table = DB.GetTable<Database.tbl_module_>();
var result = table.Where(module => module.deptCode == ((User)Session["user"]).deptCode && module.code == listModuleCode.SelectedItem.Text);
listModuleCode.Items.Remove(listModuleCode.SelectedItem);
listModuleTitle.Items.Remove(listModuleTitle.SelectedItem);
table.DeleteAllOnSubmit(result);
DB.SubmitChanges();
Response.Redirect("deletemodule.aspx"); // redirect to this page
}

We need to see your code to help more probably. However:
You need to make sure it knows to delete on submit:
var q = db.Customers.Where(c => c.CustomerID == 2).Single();
db.Customers.DeleteOnSubmit(q);
db.SubmitChanges();
Don't forget you can pass straight SQL to the object:
db.ExecuteCommand("DELETE FROM Customers WHERE ID = 2");
Which you might think is easier.

Related

How to prevent insertion in FormView?

I want to check my form before inserting to prevent insert duplicate ProductSerial in my data base.
so how can i check the txtProductSerial.text with my database and if it is duplicate I PREVENT INSERTION.
This are my codes
protected void fvwSoldForm_ItemInserting(object sender, FormViewInsertEventArgs e)
{
e.Values["DateX"] = DateTime.Now;
e.Values["IsDeleted"] = false;
e.Values["Confirmed"] = false;
var solded = db.SoldedByResellers.ToList();
solded = solded.Where(p => p.ProductSerial == NumericSerial.Text).ToList();
if (solded.Count > 0)
Alert("Please Change the serial code, This code Used before");
//Here WHAT EVER I DO THE INSERTING GOES ON. I WANT TO STOP INSERTING HERE
}
To cancel the operation, set:
e.Cancel = true;
This will prevent the insert from happening. See the MSDN documentation for an example.

How do I check a not-null query string against a sql database in c# for ASP.NET?

I have a web page that is pulling information about a specific database entry based on the reference number of that database entry. This reference number is not the SQL ID number, but a number that we assign at entry time.
This reference number is passed to the page in the form of a query string, and as long as the reference number actually exists in the database, everything is fine. However, if the reference number does not exist, my details page comes up blank: no exception or anything.
I'm not sure how relevant sharing my code is in this case, but I'll play it safe:
protected void Page_Load(object sender, EventArgs e)
{
using (KidsEntities detailEntities = new KidsEntities())
{
string imgPath = ConfigurationManager.AppSettings["imagePath"];
string KidNum = Request.QueryString["ChildNum"].ToString();
var KidSpecific = from Kid in detailEntities.Kids
where Kid.Number == KidNum
... ;
DescRepeater.DataSource = KidSpecific.ToList();
DescRepeater.DataBind();
}
}
I can put in a redirect in case some joker tries to bring up my details page without going through the main directory (which would bring up a null query string), but if used correctly, my query string will never be null or empty. What I'm trying to prepare for is if someone bookmarks my details page with a query string that was valid at the time of bookmarking, but then gets taken down.
How can I check to make sure there is a reference number in the database that matches the query string before the var "KidSpecific" fires? If there is no such reference number, I need to be able to use a Response.Redirect to put up an error page instead of the blank screen that shows now.
Thanks in advance for any help.
Why do you need to do your check before the query fires? You'll have to check the database for the entry either way. Try redirecting if your query comes up empty:
protected void Page_Load(object sender, EventArgs e)
{
using (KidsEntities detailEntities = new KidsEntities())
{
string imgPath = ConfigurationManager.AppSettings["imagePath"];
string KidNum = Request.QueryString["ChildNum"].ToString();
var KidSpecific = from Kid in detailEntities.Kids
where Kid.Number == KidNum
... ;
var KidSpecificList = KidSpecific.ToList();
//Redirect if there are no results!
if (KidSpecificList.Count() < 1)
Response.Redirect("RedirectPage.aspx");
DescRepeater.DataSource = KidSpecificList;
DescRepeater.DataBind();
}
}
You can check quety string with string.IsNullOrEmpty like this:
protected void Page_Load(object sender, EventArgs e)
{
using (KidsEntities detailEntities = new KidsEntities())
{
string imgPath = ConfigurationManager.AppSettings["imagePath"];
string KidNum = Request.QueryString["ChildNum"].ToString();
if ( string.IsNullOrEmpty ( KidNum ) ) {
Response.Redirect ( "WhatEverURI" );
} else {
var KidSpecific = from Kid in detailEntities.Kids
where Kid.Number == KidNum
... ;
DescRepeater.DataSource = KidSpecific.ToList();
DescRepeater.DataBind();
}
}
}

Create a newEventHandler for a button. But Data fields are empty for some reason

I create a new event Handler to handle two different events. One is for saving a new document. The other is for saving an edit.
I added this in my Page_load:
if (Request.QueryString["ExhibitID"] != null)//new
{
if (!IsPostBack)
{
ddlCaseFiles.DataSourceID = "dsCaseFiles";
ddlCaseFiles.DataTextField = "Display";
ddlCaseFiles.DataValueField = "FileID";
rbByFileID.Checked = true;
rbMyFiles.Checked = false;
ddlCaseFiles.DataBind();
editExhibit(int.Parse(Request.QueryString["ExhibitID"]));//new
exhibitHeader.InnerText = "Edit Exhibit";
}
hidSavedExhibitID.Value = Request.QueryString["ExhibitID"];
saveExhibitBtn.Click += new EventHandler(this.btnUpdateExhibit_Click);
}
else
{
saveExhibitBtn.Click += new EventHandler(this.saveExhibitBtn_Click);
}
my save method for some reason keeps looping then crashing because the second time it goes through, there is no data since I reset it after the first save. I have no idea why it is running my save method twice.
this is my save method :
protected void saveExhibitBtn_Click(object sender, EventArgs e)
{
hidSavedExhibitID.Value = null;
int newExhibitID = saveExhibit();
int propertyID = autoCreateProperty(newExhibitID);
linkExhibitAndProperty(newExhibitID, propertyID);
SaveInfoIntoSessionVariables();
ClearFormFields();
}
the "saveExhibit()" method is where I actually access the DB and store everything. It works fine.
Because you re bind your datas in your Page_Load.
You must persist your datas with ViewState, EnableViewState="true"
You bind your datas just one time, in the ! IsPostBack. in order to not erase the selected values
If(! IsPostBack)
{
//Bind your datas with `DataBind()`
}

Selected value in asp.net dropdown in a repeater not returned

I've currently go a very strange problem. I'm using an asp.net wizard to upload some files. The files are uploaded using plupload. After the files have uploaded I have a list of the upload files stored in a session variable. I use the session variable to create a table showing the upload files. The user now has option to set a file category using a dropdown in the table. When the user clicks 'finish' button the code reads the list of files and the category from the table. The odd thing is this code works fine on my development machine and on several servers but on a particular clients server the drop down value always returns as null. Here is the relevent code:
protected void Page_Init(object sender, EventArgs e)
{
bindRepeater();
}
private void bindRepeater()
{
ArrayList sessionFiles = (ArrayList)Session["PLUploadFiles"];
IList<document> files = new List<document>();
foreach (string fileName in sessionFiles)
{
document doc = new document();
doc.FileName = fileName;
doc.Description = fileName.Split('.').First();
files.Add(doc);
}
TableRepeater.DataSource = files;
TableRepeater.DataBind();
}
protected void SaveButton_Click(object sender, EventArgs e)
{
foreach (RepeaterItem item in TableRepeater.Items)
{
Label descriptionLabel = (Label) item.FindControl("DescriptionLabel");
String description = descriptionLabel.Text;
Label fileNameLabel = (Label)item.FindControl("FileNameLabel");
String fileName = fileNameLabel.Text;
DropDownList categoryDropDown = (DropDownList) item.FindControl("CategoryDropDownList");
string category = categoryDropDown.SelectedValue;
if(SaveClicked != null)
{
SaveEventArgs s = new SaveEventArgs();
s.FileName = fileName;
s.Category = category;
s.Description = description;
SaveClicked(this, s);
}
}
Response.Redirect(RedirectURL);
}
Note that the entire wizard lives on a usercontrol. Has anybody got any idea why this code works fine on most machines but fails on one particular server?
Looks like I've fixed it. For some reason I was seeing a double postback. This was calling my code to reset the session variables in Page_Load at the wrong time. The work around is to reset the session variables in the page that links to the upload page so they are reset before the page is loaded. I've no idea why I'm seeing the double postback.

delete record onClick, asp.net

I have a form where users can subscribe and unsubcribe to my email list. so far, i have the subscribe button working fine "add member" function. Now i need help with my "delete member " function (unsubscribe button). it will allows the user to delete their record from the database. When I run the code and click the "unsubscribe" button, i can't get the logic correct so that it will delete the user's record if it exisit. thanks for your help!
here's the code i'm using for the subscribe and unsubscribe buttons -----------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class joinmailinglist : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void addMember(object sender, EventArgs e)
{
// here you are defining the classes for the database and the linq
mailinglistClassDataContext Class = new mailinglistClassDataContext();
mailinglistMember member = new mailinglistMember();
// Now we are going to add the data to the member
// Here we are going to let the system define a GUID for the unique user ID
member.memberID = new Guid();
// here we are going to capture the user inputs and we are going to set these to lower case especially the email so that we can do a proper comparison later.
member.fname = txtFirstName.Text;
member.lname = txtLastName.Text;
member.email = txtEmail.Text;
// Here we are going to create the URL so we can later remove the user if they decide to opt out.
member.removeurl = "http://removeuser.aspx?code=" + member.memberID.ToString();
// Here we are going to use a LINQ query to search the class of mailinglistmembers for any emails that contain equal values of the text field and select it.
var duplicatecheck = from emails in Class.mailinglistMembers
where emails.email.Contains(txtEmail.Text)
select emails;
// Here we are going to check that the count of duplicate is equal to zero. If so then we are going to insert the member information into the class and then submit the changes to the database.
if (duplicatecheck.Count() == 0)
{
Class.mailinglistMembers.InsertOnSubmit(member);
Class.SubmitChanges();
}
else
{
lblDuplicate.Text = "Hey you have already entered your information.";
}
}
protected void deleteMember(object sender, EventArgs e)
{
// here you are defining the classes for the database and the linq
mailingListClassDataContext Class = new mailingListClassDataContext();
mailinglistMember member = new mailinglistMember();
// here we are going to capture the user inputs and we are going to set these to lower case especially the email so that we can do a proper comparison later.
member.email = txtEmail.Text;
// Here we are going to use a LINQ query to search the class of mailinglistmembers for any emails that contain equal values of the text field and select it.
var deleterec = from emails in Class.mailinglistMembers
where emails.email.Contains(txtEmail.Text)
select emails;
// Here we check if the record exisits
if (deleterec.Count() == 0)
{
Class.mailinglistMembers.DeleteOnSubmit(member);
Class.SubmitChanges();
Response.Redirect("frm_confirmation.aspx");
}
else
{
lblDelete.Text = "No record exsists!";
}
}
}
Try the below code.
string mailAddress = txtEmail.Text.Trim().ToLower();
using (var db = new mailingListClassDataContext())
{
var records = from e in db.mailinglistMembers
where e.mail == mailAddress
select e;
if (records != null)
{
db.mailinglistMembers.DeleteAllOnSubmit(records);
db.SubmitChanges();
Response.Redirect("frm_confirmation.aspx");
Response.End();
}
else
{
lblDelete.Text = "No records exists!";
}
}
You may have meant to do this:
var deleterec = Class.mailinglistMembers
.FirstOrDefault(emails => emails.email.Contains(txtEmail.Text));
if (deleterec != null)
{
Class.mailinglistMembers.DeleteOnSubmit(deleterec);
Class.SubmitChanges();
Response.Redirect("frm_confirmation.aspx");
}
Looks like someone tried to add on to the code I origianlly posted in my article on code project. Not sure if you've read the article but it might help solve your problem and understand how it was intended to work. A link would return you to a removal page that would and capture the GUID. I used the GUID as the identifyer to remove the user. Original Article

Resources