Exception handling in WebForms - c#

I have a webform with a formview
<asp:FormView ID="formViewBrouwers" runat="server" AllowPaging="True"
DataKeyNames="BrouwerNr" DataSourceID="brouwerDataSource"
onitemupdated="formViewBrouwers_ItemUpdated"
onitemupdating="formViewBrouwers_ItemUpdating"
oniteminserted="formViewBrouwers_ItemInserted"
oniteminserting="formViewBrouwers_ItemInserting">
<EditItemTemplate>
BrouwerNr:
<asp:Label ID="BrouwerNrLabel1" runat="server"
Text='<%# Eval("BrouwerNr") %>' />
<br />
BrNaam:
<asp:TextBox ID="BrNaamTextBox" runat="server" Text='<%# Bind("BrNaam") %>' />
<br />
Adres:
<asp:TextBox ID="AdresTextBox" runat="server" Text='<%# Bind("Adres") %>' />
<br />
Postcode:
<asp:TextBox ID="PostcodeTextBox" runat="server"
Text='<%# Bind("Postcode") %>' />
<br />
Gemeente:
<asp:TextBox ID="GemeenteTextBox" runat="server"
Text='<%# Bind("Gemeente") %>' />
<br />
Omzet:
<asp:TextBox ID="OmzetTextBox" runat="server" Text='<%# Bind("Omzet") %>' />
<br />
Status:
<asp:TextBox ID="StatusTextBox" runat="server" Text='<%# Bind("Status") %>' />
<br />
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True"
CommandName="Update" Text="Update" />
<asp:LinkButton ID="UpdateCancelButton" runat="server"
CausesValidation="False" CommandName="Cancel" Text="Cancel" />
</EditItemTemplate>
<InsertItemTemplate>
BrNaam:
<asp:TextBox ID="BrNaamTextBox" runat="server" Text='<%# Bind("BrNaam") %>' />
<br />
Adres:
<asp:TextBox ID="AdresTextBox" runat="server" Text='<%# Bind("Adres") %>' />
<br />
Postcode:
<asp:TextBox ID="PostcodeTextBox" runat="server"
Text='<%# Bind("Postcode") %>' />
<br />
Gemeente:
<asp:TextBox ID="GemeenteTextBox" runat="server"
Text='<%# Bind("Gemeente") %>' />
<br />
Omzet:
<asp:TextBox ID="OmzetTextBox" runat="server" Text='<%# Bind("Omzet") %>' />
<br />
Status:
<asp:TextBox ID="StatusTextBox" runat="server" Text='<%# Bind("Status") %>' />
<br />
<asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True"
CommandName="Insert" Text="Insert" />
<asp:LinkButton ID="InsertCancelButton" runat="server"
CausesValidation="False" CommandName="Cancel" Text="Cancel" />
</InsertItemTemplate>
<ItemTemplate>
BrouwerNr:
<asp:Label ID="BrouwerNrLabel" runat="server" Text='<%# Eval("BrouwerNr") %>' />
<br />
BrNaam:
<asp:Label ID="BrNaamLabel" runat="server" Text='<%# Bind("BrNaam") %>' />
<br />
Adres:
<asp:Label ID="AdresLabel" runat="server" Text='<%# Bind("Adres") %>' />
<br />
Postcode:
<asp:Label ID="PostcodeLabel" runat="server" Text='<%# Bind("Postcode") %>' />
<br />
Gemeente:
<asp:Label ID="GemeenteLabel" runat="server" Text='<%# Bind("Gemeente") %>' />
<br />
Omzet:
<asp:Label ID="OmzetLabel" runat="server" Text='<%# Bind("Omzet") %>' />
<br />
Status:
<asp:Label ID="StatusLabel" runat="server" Text='<%# Bind("Status") %>' />
<br />
<asp:LinkButton ID="EditButton" runat="server" CausesValidation="False"
CommandName="Edit" Text="Edit" />
<asp:LinkButton ID="DeleteButton" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete" />
<asp:LinkButton ID="NewButton" runat="server" CausesValidation="False"
CommandName="New" Text="New" />
</ItemTemplate>
<PagerSettings Mode="NextPreviousFirstLast" />
</asp:FormView>
In my property Postcode I check the value like this:
private Int16 postcodeValue;
public Int16 Postcode
{
get
{
return postcodeValue;
}
set
{
if (value < 1000 || value > 9999)
{
throw new Exception("Postcode moet tussen 1000 en 9999 liggen");
}
else
{
postcodeValue = value;
}
}
}
How can I handle the exception I threw? If there is an exception I want a label to appear with the following exception?

You can associate the PostCode textbox in InsertItemTemplate and EditItemTemplate with a RangeValidator and have a label beside that shows the error message when the condition fails.

Maybe you should use a derived exception type, like ArgumentException or a custom class, something like PostCodeException.
This way you can catch the correct exception type and react accordingly.
This article may be useful: http://msdn.microsoft.com/en-us/library/ms173160(v=VS.100).aspx

You could use a RegularExpressionValidator or RangeValidator that would validate the value on the client side before submitting it to the server.
This '^[1-9]{1}[0-9]{3} ?[A-Z]{2}$' would be a valid regex to check a Dutch postal code.
Or instead of throwing an exception in your property setter, you could show a label that is normally hidden in your markup.
If you really want to throw an exception have a look at the Page_Error event. You can use that to catch all exceptions in your page and handle them if appropriately.

Related

Why does asp.net display table name instead of table field

im working on a project and im combining 3 tables the tables are already associated in the dbml but my problem is when i use the data list it diaplays my table names not the correct fields this is a college assignment but i have tried everything i know to do.
I've tried to combine them seperatly in sql manager in vs but im just not understanding why it isn't showing the correct thing
<form id="form1" runat="server">
<div>
<asp:LinqDataSource ID="LinqDataSource1" runat="server" ContextTypeName="assign_6_final.DataClasses1DataContext" EntityTypeName="" Select="new (CustomerID, Name)" TableName="Customers">
</asp:LinqDataSource>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" DataSourceID="LinqDataSource1" DataTextField="Name" DataValueField="CustomerID" OnSelectedIndexChanged="Page_Load">
</asp:DropDownList>
<asp:DataList ID="DataList1" runat="server" DataSourceID="LinqDataSource2" Font-Bold="False" Font-Italic="False" Font-Overline="False" Font-Strikeout="False" Font-Underline="False" OnSelectedIndexChanged="DataList1_SelectedIndexChanged" OnDataBinding="DataList1_SelectedIndexChanged">
<ItemTemplate>
IncidentID:
<asp:Label ID="IncidentIDLabel" runat="server" Text='<%# Eval("IncidentID") %>' />
<br />
DateOpened:
<asp:Label ID="DateOpenedLabel" runat="server" Text='<%# Eval("DateOpened") %>' />
<br />
DateClosed:
<asp:Label ID="DateClosedLabel" runat="server" Text='<%# Eval("DateClosed") %>' />
<br />
Title:
<asp:Label ID="TitleLabel" runat="server" Text='<%# Eval("Title") %>' />
<br />
Description:
<asp:Label ID="DescriptionLabel" runat="server" Text='<%# Eval("Description") %>' />
<br />
CustomerID:
<asp:Label ID="CustomerIDLabel" runat="server" Text='<%# Eval("CustomerID") %>' />
<br />
Technician:
<asp:Label ID="TechnicianLabel" runat="server" Text='<%# Eval("Technician") %>' />
<br />
Product:
<asp:Label ID="ProductLabel" runat="server" Text='<%# Eval("Product") %>' />
<br />
<br />
<br />
</ItemTemplate>
</asp:DataList>
</div>
<asp:LinqDataSource ID="LinqDataSource2" runat="server" ContextTypeName="assign_6_final.DataClasses1DataContext" EntityTypeName="" Select="new (IncidentID, DateOpened, DateClosed, Title, Description, CustomerID, Technician, Product)" TableName="Incidents" Where="CustomerID = #CustomerID">
<WhereParameters>
<asp:ControlParameter ControlID="DropDownList1" Name="CustomerID" PropertyName="SelectedValue" Type="Int32" />
</WhereParameters>
</asp:LinqDataSource>
<asp:EntityDataSource ID="EntityDataSource1" runat="server">
</asp:EntityDataSource>
</form>
</body>
the outcome i expected was that the last 2 items the product and technician would output correctly but they haven't and im kind of lost my teacher said this is a common problem in asp but ive never seen it
Try using the following and so forth:
<%# DataBinder.Eval(Container.DataItem,"CustomerID") %>

ValidationGroup on Fileupload

I have a FormView where there is a FileUpload with a RequiredFieldValidator and I need to have a validationGroup on the FileUpload or else my Button won't go it's PostBackUrl.
My code:
<asp:FormView ID="fwResultsInsert" runat="server" DataKeyNames="ResultsID"
DataSourceID="ObjResults" DefaultMode="Insert">
<InsertItemTemplate>
<asp:Label ID="lblImagess" runat="server" Text="Resultat Billede:"></asp:Label>
<asp:FileUpload ID="fuResultsImages" runat="server" />
<asp:RequiredFieldValidator ID="rfvImage" runat="server" ErrorMessage="*Her mangler noget!!" ControlToValidate="fuResultsImages"></asp:RequiredFieldValidator>
<asp:Label ID="lblOutput" runat="server" Text="" Visible="True"></asp:Label>
<asp:Label ID="Error" runat="server" Text="" Visible="True"></asp:Label>
<asp:ImageButton ID="imgPicture" runat="server" Visible="True" />
<br />
<asp:LinkButton ID="btnInsert" runat="server" CausesValidation="True"
CommandName="Insert" Text="Insæt" onclick="btnInsert_Click" ForeColor="#000000" Font-Underline="True" />
<asp:LinkButton ID="btnCancel" runat="server"
CausesValidation="False" CommandName="Cancel" Text="Fortryd" ForeColor="#000000" Font-Underline="True" />
</InsertItemTemplate>
</asp:FormView>
<asp:Button ID="btnHome" runat="server" Text="Forsiden" PostBackUrl="~/BackEnd/Default.aspx" />
I need to have some kind of validation on my FileUpload, so there have to be something in the fileupload-box when I clink insert, atm I have a RequiredFieldValidator, but there is a conflict with another Button I have outside the FormView, atm when I click the button nothing happens unless there is something in the FileUpload, and that's not the point.
Add CausesValidation="false" to the Button which you have outside the FormView.
Ex:
<asp:Button ID="btnHome" runat="server" Text="Forsiden" PostBackUrl="~/BackEnd/Default.aspx" CausesValidation="false" OnClick="btnHome_Click" />

Passing Eval value to C# method for shopping cart

I am creating a shopping cart web app for my class. When the user clicks on the add to cart button, I want to pass the value of the ID of each specific product to a separate method in the code behind. Not sure if my syntax is off or if this just wont work. Here is my mark up:
<asp:Button ID="AddToCart" CommandName="Add"
OnClientClick ='<%# ListView1_AddToCart(Eval("ID"))%>'
CssClass ="Button" runat="server" Text="Add to Cart" />
Here is my code behind:
public void ListView1_AddToCart(string CatID)
{cart.AddToCart(CatID);}
I keep getting various issues, but this gives me the following error:
The best overloaded method match for 'OurCats_GrumpyCats.ListView1_AddToCart(string)'
has some invalid arguments.
How can I resolve this? Is there any better way?
EDIT: Here is my mark up
<%# Page Title="All Cats" Language="C#" MasterPageFile="~/MasterPage/Layout.master" AutoEventWireup="true" CodeFile="AllCats.aspx.cs" Inherits="OurCats_GrumpyCats" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="cpMainContent" Runat="Server">
<h1>Meet all of our kittens!</h1>
<asp:ListView ID="ListView1" runat="server" DataKeyNames="ID" DataSourceID="SqlDataSource2">
<EmptyDataTemplate>
<span>No data was returned.</span>
</EmptyDataTemplate>
<InsertItemTemplate>
<span style="">ID:
<asp:TextBox ID="IDTextBox" runat="server" Text='<%# Bind("ID") %>' />
<br />
Name:
<asp:TextBox ID="NameTextBox" runat="server" Text='<%# Bind("Name") %>' />
<br />
Price:
<asp:TextBox ID="PriceTextBox" runat="server" Text='<%# Bind("Price") %>' />
<br />
Imgu:
<asp:TextBox ID="ImguTextBox" runat="server" Text='<%# Bind("Img") %>' />
<br />
Description:
<asp:TextBox ID="DescriptionTextBox" runat="server" Text='<%# Bind("Description") %>' />
<br />
<asp:Button ID="InsertButton" runat="server" CommandName="Insert" Text="Insert" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Clear" />
<br />
<br />
</span>
</InsertItemTemplate>
<ItemTemplate>
<table class ="Table" style="border-style: solid; ">
<tr>
<td >
<a href ="Details.aspx?ID=<%# Eval("ID")%>">
<img src="../Images/<%# Eval("Img") %>" width ="200" />
</a>
</td>
<td style="width:700px; margin-left: 100px">
<asp:Label ID="Label1" runat="server" Text="Name: "></asp:Label><asp:Label ID="NameLabel" runat="server" Text='<%# Eval("Name") %>' />
<asp:Textbox ID="CatID" runat="server" Visible="false" Text='<%# Eval("ID")%>'></asp:Textbox>
<br />
<br />
<asp:Label ID="Label2" runat="server" Text="Price: $"></asp:Label><asp:Label ID="PriceLabel" runat="server" Text= '<%# Eval("Price") %>'/>
<br />
<br />
<asp:Label ID="Label3" runat="server" Text="Description: "></asp:Label><asp:Label ID="DescriptionLabel" runat="server" Text= '<%# Eval("Description") %>' />
<br />
<br />
<asp:Button ID="AddToCart" CommandName="Add" OnClientClick='<%# "AddToCart(" +Eval("ID") + " );" %>' CssClass ="Button" runat="server" Text="Add to Cart" />
</td>
</tr>
</table>
</ItemTemplate>
<LayoutTemplate>
<div id="itemPlaceholderContainer" runat="server" style =" margin-left :30px;">
<span runat="server" id="itemPlaceholder" />
</div>
<div style="">
</div>
</LayoutTemplate>
</asp:ListView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:420_Project_GLConnectionString1 %>" SelectCommand="SELECT * FROM [OurCats]">
</asp:SqlDataSource>
</asp:Content>
try below code
<asp:Button ID="AddToCart" CommandName="Add"
OnClientClick ='<%# ListView1_AddToCart((string)Eval("ID"))%>'
CssClass ="Button" runat="server" Text="Add to Cart" />
OnClientClick ='<%# "ListView1_AddToCart(" +Eval("ID") + " );" %>'

Problem with Validation Control in formview ASP.NET C#

I'm having some problem with validation control in formview. I could add a validation control inside a formview control it was working fine until I tried to group them using validationgroups. Also if I dont enter a value the program still allow to add it in the database. Could someone help me point out the problem or error in my program? Here's the Insert statement I've made.
<InsertItemTemplate>
Book ID:
<asp:TextBox ID="bookidTextBox" runat="server" Text='<%# Bind("bookid") %>' />
<asp:RequiredFieldValidator ID="RequesFieldValidator1" runat="server" ErrorMessage="* Required" ControlToValidate="bookidTextBox" ValidationGroup="InsertBook">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator" runat="server" Display="Dynamic" ControlToValidate="bookidTextBox" ValidationExpression="^([\S\s]{13,13})$" ErrorMessage="Value must be at least 13 characters long">
</asp:RegularExpressionValidator>
<br />
Title:
<asp:TextBox ID="booktitleTextBox" runat="server"
Text='<%# Bind("booktitle") %>' />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="* Required" ControlToValidate="booktitleTextBox" ValidationGroup="InsertBook">
</asp:RequiredFieldValidator>
<br />
Author's lastname:
<asp:TextBox ID="lastnameTextBox" runat="server"
Text='<%# Bind("lastname") %>' />
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="* Required" ControlToValidate="lastnameTextBox" ValidationGroup="InsertBook">
</asp:RequiredFieldValidator>
<br />
Author's firstname:
<asp:TextBox ID="firstnameTextBox" runat="server"
Text='<%# Bind("firstname") %>' />
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="* Required" ControlToValidate="firstnameTextBox" ValidationGroup="InsertBook">
</asp:RequiredFieldValidator>
<br />
Description:
<asp:TextBox ID="descriptionTextBox" runat="server"
Text='<%# Bind("description") %>' />
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ErrorMessage="* Required" ControlToValidate="descriptionTextBox" ValidationGroup="InsertBook">
</asp:RequiredFieldValidator>
<br />
Category:
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="categoryDataSource" DataTextField="name"
DataValueField="categoryid" SelectedValue='<%# Bind("categoryid", "{0}") %>'>
</asp:DropDownList>
<asp:SqlDataSource ID="categoryDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:LibrarySystemConnectionString %>"
SelectCommand="SELECT [categoryid], [name] FROM [TblCategory]">
</asp:SqlDataSource>
<br />
Date added:
<asp:TextBox ID="dateaddedTextBox" runat="server"
Text='<%# Bind("dateadded") %>' />
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ErrorMessage="* Required" ControlToValidate="dateaddedTextBox" ValidationGroup="InsertBook">
</asp:RequiredFieldValidator>
<br />
Status:
<asp:DropDownList ID="DropDownList2" runat="server"
DataSourceID="statusDataSource" DataTextField="statusname"
DataValueField="statusid" SelectedValue='<%# Bind("statusid", "{0}") %>'>
</asp:DropDownList>
<asp:SqlDataSource ID="statusDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:LibrarySystemConnectionString %>"
SelectCommand="SELECT [statusid], [statusname] FROM [BookStatus]">
</asp:SqlDataSource>
<br />
Quantity:
<asp:TextBox ID="quantityTextBox" runat="server"
Text='<%# Bind("quantity") %>' />
<asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server" ErrorMessage="* Required" ControlToValidate="quantityTextBox" ValidationGroup="InsertBook">
</asp:RequiredFieldValidator>
<br />
<asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True" CommandName="Insert" Text="Add" />
<asp:LinkButton ID="InsertCancelButton" runat="server"
CausesValidation="False" CommandName="Cancel" Text="Cancel" />
</InsertItemTemplate>
Any help would be much appreciated ;)
Thanks in advance.
You have to set ValidationGroup="InsertBook" as you have set Validation group to your validation.
<asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True" CommandName="Insert"
Text="Add" ValidationGroup="InsertBook" />

Usercontrols which don't trigger events for visitors

This UpdatePanel is contained by an UserControl. When the LinkButton is pressed arow should be added in another GridView. When an user is logged in this control is working well.
The problems appears when an user is not logged in and try to push that button. No event triggers.
Someone suggested me to give a permission for accessing this control in web.config. That didn't work.
Anyone has another idea?
<asp:UpdatePanel runat="server" UpdateMode="Conditional" EnableViewState="true" ID="IngredientsUpdatePanel">
<ContentTemplate>
<asp:ObjectDataSource ID="sourceIngredients" runat="server" SelectMethod="GetAll">
</asp:ObjectDataSource>
<asp:GridView ID="Ingredients" AllowPaging="true" runat="server" DataKeyNames="IngredientId"
EnableViewState="true" DataSourceID="sourceIngredients" PageSize="5"
AutoGenerateColumns="false" HorizontalAlign="Center" OnSelectedIndexChanged="Ingredients_SelectedIndexChanged">
<RowStyle HorizontalAlign="Center" />
<HeaderStyle Font-Bold="true" ForeColor="Black" />
<Columns>
<asp:TemplateField HeaderText="Ingrediente" ItemStyle-Font-Size="10">
<ItemTemplate>
<asp:Label ID="lblId" Text='<%# Bind("IngredientId") %>' Visible="false" runat="server"/>
<asp:Label ID="lblPrice" Text='<%# Bind("Price") %>' Visible="false" runat="server"/>
<asp:Label ID="lblDescr" Text='<%# Bind("Description") %>' Visible="false" runat="server"/>
<asp:Label ID="lblName" Text='<%# Bind("Name") %>' Visible="false" runat="server"/>
<asp:Label ID="lblPict" Text='<%# Bind("Picture") %>' Visible="false" runat="server"/>
<div style="text-align:left;">
<img id="img" style="float:right;" src='<%# Eval("Picture") %>'
height="75" runat="server" alt="Picture" />
<b>
<%# Eval("Name") %>
</b>
<br />
<br />
Price: <b><%# Eval("Price") %></b>
<br />
<br />
<br />
</div>
<hr />
<div style="text-align:left;">
<b>Description</b>
</div>
<div style="width:300px;">
<%# Eval("Description") %>
</div>
<br />
<asp:LinkButton Enabled="true" runat="server" Text="Add" CommandName="Select" ID="cmdAdd" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
I solved the problem in a tricky way.
I deleted the LinkButton and before TemplateField I put a ButtonField and all is working fine.
Now the code looks like:
<Columns>
<asp:ButtonField Text="Add" CommandName="Select" />
<asp:TemplateField>
......
</asp:TemplateField>
</Columns>
Still I'm not understanding why the control had that behavior.
Don't forget to give the webresource.axd enough rights in the web.config?

Categories

Resources