How to prevent insertion in FormView? - asp.net

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.

Related

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()`
}

Can't submit changes to database or page controls

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.

show popupcontrol in rowupdating event of devexpress gridview, if a certain criteria fails

I have a Devexpress Gridview where item and it's price is displayed.
Editing is enabled.
I use rowupdating event so inorder to check if the price updated is higher than a normal value.
if so, i cancel edit by
e.Cancel = true;
ASPxGridView1.CancelEdit();
the next thing i want is to popup a aspx popupcontrol requesting a password inorder to proceed with higher amount within the rowupdating event.
the popcontrol will contain a password textbox and a button.The remaining procces will be carried out by button click function
eventhough i called popcontrol
ASPxPopupControl2.ShowOnPageLoad = true;
the pop doesn't show up......why is this so..
here is my over all code..
protected void ASPxGridView1_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
{
string msg;
double new_amt = double.Parse(e.NewValues["Amount"].ToString());//-->gets new amount
string type= e.OldValues["Type"].ToString();//-->gets the item
double refer_amt=Misc_functions.Get_Item_Amount(type,out msg);//--this function fetches the normal amount for a particular item
if (new_amt > refer_amt)
{
e.Cancel = true;
ASPxGridView1.CancelEdit();
ASPxPopupControl2.ShowOnPageLoad = true;
}
}
Basically i need a password authentication if an amount edited is a higher than a normal value.
any ideas??
This cannot be done using the server code. The best solution is to create a custom java script variable within the RowUpdating event handler and check its value in the ASPxGridView's client side EndCallback event handler. I.e.
protected void ASPxGridView1_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
{ ...
gridView.JSProperties["cpShowPopup"] = true;
...
}
EndCallback = function(s,e) {
if(typeof(s.cpShowPopup) != 'undefined') {
popup.Show();
}
}
Hope, this helps.

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