Markup getting erased in VS 2008 - asp.net

I am using master pages, update panel, AJAX Tab container and also modalpopup extenders and other AJAX validation controls. The line that is bold for Termination Reaon has a problem. I need to have <asp:ListItem Text="Select Contract Termination Reason.." Value=""></asp:ListItem> to control the error:
'ddlContractTerminationReason' has a SelectedValue which is invalid because it does not exist in the list of items"
It works but suddenly it started getting erased while trying to make some other changes to the application. If I try to type that again as soon as I click on Save, it gets erased and saves the file. My network administrator reinstalled everything for me assuming that some virus problem but looks like something else is causing this. Any help on this greatly appreciated.
<tr>
<td>
<asp:DropDownList ID="ddlContractTerminationReason" runat="server" AppendDataBoundItems="True" CausesValidation="True" CssClass="dropdown extralong" DataSourceID="dsTerminationReason" DataTextField="ReasonDescription" DataValueField="TerminationReasonID">
<asp:ListItem Text="Select Contract Termination Reason.."></asp:ListItem>
</asp:DropDownList>
<asp:CustomValidator ID="cusValTerminationReason" runat="server" ClientValidationFunction="RequireTerminationReason" ControlToValidate="ddlContractTerminationReason" ErrorMessage="Please enter Termination Reason OR Other Resson, if the Contractor is Terminated!" OnServerValidate="ServerValidateTerminationDate" SetFocusOnError="True" Text="*" ValidateEmptyText="True" ValidationGroup="ContrMasterGroup"></asp:CustomValidator>
<asp:SqlDataSource ID="dsTerminationReason" runat="server" ConnectionString="<%$ ConnectionStrings:Conn %>" SelectCommand="SELECT [TerminationReasonID], [ReasonDescription] FROM [TerminationReasons] ORDER BY [ReasonDescription]"> </asp:SqlDataSource>
</td>
<td class="rightalign">
<asp:Label ID="lblOtherContractTerminationReason" runat="server" CssClass="lbl" Text="if Others, Explain:"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtOtherContractTerminationReason" runat="server" CssClass="long" TextMode="MultiLine"></asp:TextBox>
</td>
<td> </td>
</tr>

After your DataBind execute this code
ddlContractTerminationReason.DataBind();
ddlContractTerminationReason.Items.Add("Select Contract Termination Reason..");

Related

How to perform custom error handling for update command of ASPX's ViewForm?

I'm learning the use of ASPX's DataControls, and I have succesfully used a FormView and its corresponding SqlDataSource to call stored procedures for select and update commands, that is, both comands are of type "StoredProcedure". I'm using VisualStudio 2012, with aspx pages and vb code. Not using ajax nor jquery.
The stored procedure for insert or update performs validations before attempting any DML, If a validation is not met, the stored procedure would return 0 (false) in #psiSuccess (output param of type Bit) and a descriptive message in #psvMessage (output param of type VarChar).
I want the UI to inform the validation not met, so the user has the chance to correct the input and re-try, preserving the attempted values so only the wrong field has to be corrected. This is easily achieved when I manually create my forms, I just can't find the proper settings for these controls to do the same
I tried to evaluate the output parameter and in case of "no success", display the error message and keep the ViewForm in edit mode, keeping most of the user input to make it easier for the user to correct the failing field and re try.
I have used the SqlDataSource's "OnUpdated" event (SqlDataSource1_Updated(sender As Object, e As SqlDataSourceStatusEventArgs)) where I can actually examine the value of the output parameters and change a Label's text to reflect the error message, however, the FormView returns to Read Only mode (the page actually reloads).
I have called the FormView's ChangeMode Method, but it appears not to work. However, I'm certain the code is executing.
How can I keep edit mode or return to edit mode on the FormView?
This is the code I have used in the onUpdated Event:
Protected Sub sqldsProyecto_Updated(sender As Object, e As SqlDataSourceStatusEventArgs)
Dim success As Boolean = e.Command.Parameters("#psiSuccess").Value.ToString.Equals("True")
Dim message As String = e.Command.Parameters("#psvMessage").Value.ToString()
If Not success Then
lblMensaje.Text = mensaje
fvProyecto.ChangeMode(FormViewMode.Edit)
Response.Output.WriteLine("<script>alert('" + message + "')</script>")
End If
End Sub
The alert is actually shown by the browser and it contains the error message that comes from the stored procedure, but the FormView (fvProyecto) is shown in ReadOnly mode.
Edit 1
I performed a test to evaluate the order of execution of the events and it is:
<!--This is page Load-->
<!--This is sqldsProyecto_Updating -->
<!--This is sqldsProyecto_Updated-->
So, if the setting in ChangeMode is being overridden, setting it in Page_Load would still be overridden, since it happens before _Updating and _Updated events.
By this logic, testing for statement completion in Page_Loag will allways return false, since the action is performed after that, unless ASPX reports the events in some different order.
Is there some other property that must be set in order for ChangeMode to persist until page is rendered?
Edit 2
Here is the SqlDataSource, declared right after <body>:
<asp:SqlDataSource ID="sqldsProyecto" runat="server" SelectCommandType="StoredProcedure" SelectCommand="pObtieneProyecto" UpdateCommand="pActualizaProyecto" UpdateCommandType="StoredProcedure" OnUpdating="sqldsProyecto_Updating" OnUpdated="sqldsProyecto_Updated" ConnectionString="<%$ ConnectionStrings: cnxKanban %>" CancelSelectOnNullParameter="false">
<SelectParameters><!-- 2 parameters -->
</SelectParameters>
<UpdateParameters>
<!-- 11 input parameters -->
<asp:ControlParameter Name="psiSuccess" Direction="Output" Type="Boolean" ControlID="fvProyecto$hdnSuccess" PropertyName="Value" />
<asp:ControlParameter Name="psvMessage" Direction="Output" Type="String" Size="-1" ControlID="fvProyecto$lblMessage" PropertyName="Text" />
</UpdateParameters>
</asp:SqlDataSource>
Here is the FormView, declared inside a <div> inside <form id="form1" runat="server">
<asp:FormView ID="fvProject" runat="server" DataSourceID="sqldsProyecto" Width="100%">
<HeaderStyle CssClass="h2" />
<HeaderTemplate>
←
<asp:Label id="lblProjectName" runat="server" Text='<%# Eval("projectName")%>' />
</HeaderTemplate>
<ItemTemplate>...</ItemTemplate>
<EditItemTemplate>
<table class="formview-item-table">
<tr>
<th style="width: 130px;">Name:</th>
<td><asp:TextBox ID="txtProjectName" runat="server" Text='<%# Eval("projectName")%>' style="width: 400px;"></asp:TextBox></td>
</tr>
<tr>
<th>Description:</th>
<td><asp:TextBox ID="txtDescription" runat="server" Text='<%# Eval("description")%>' TextMode="MultiLine" Height="4em" Rows="3"></asp:TextBox></td>
</tr>
<tr>
<th>Kanban: </th>
<td>
<asp:DropDownList ID="selectKanban" runat="server" DataSourceID="sqldsTableros" DataValueField="idKanban" DataTextField="kanban" SelectedValue='<%# Eval("idKanban")%>'></asp:DropDownList>
</td>
</tr>
<tr>
<th>Estado</th>
<td>
<asp:DropDownList ID="selectStatus" runat="server" DataSourceID="sqldsStatus" DataValueField="idStatus" DataTextField="status" SelectedValue='<%# Eval("idStatus")%>'>
</asp:DropDownList>
</td>
</tr>
<tr>
<th>Priority</th>
<td>
<asp:ListBox ID="selectPriority" runat="server" Rows="1" SelectedValue='<%# Eval("priority")%>'>
<asp:ListItem Value="10">10 (Maximum)</asp:ListItem>
<asp:ListItem Value="9">9</asp:ListItem>
<asp:ListItem Value="8">8</asp:ListItem>
<asp:ListItem Value="7">7</asp:ListItem>
<asp:ListItem Value="6">6</asp:ListItem>
<asp:ListItem Value="5">5</asp:ListItem>
<asp:ListItem Value="4">4</asp:ListItem>
<asp:ListItem Value="3">3</asp:ListItem>
<asp:ListItem Value="2">2</asp:ListItem>
<asp:ListItem Value="1">1 (Minimum)</asp:ListItem>
<asp:ListItem Value="0">0</asp:ListItem>
</asp:ListBox>
</td>
</tr>
<tr>
<th>Estimated duration</th>
<td>
<asp:TextBox ID="txtEstimatedDuration" runat="server" Text='<%# Eval("estimatedDuration")%>'></asp:TextBox> días</td>
</tr>
<tr>
<th>Responsable:</th>
<td>
<asp:DropDownList ID="selectResponsable" runat="server" DataSourceID="sqldsParticipantes" DataValueField="idParticipante" DataTextField="nombreParticipante" SelectedValue='<%# Eval("idResponsable")%>' AppendDataBoundItems="true">
<asp:ListItem Selected="True" Value="">(ninguno)</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<th>Requirente:</th>
<td>
<asp:DropDownList ID="selectRequiriente" runat="server" DataSourceID="sqldsParticipantes" DataValueField="idParticipante" DataTextField="nombreParticipante" SelectedValue='<%# Eval("idRequiriente")%>' AppendDataBoundItems="true">
<asp:ListItem Selected="True" Value="">(ninguno)</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td colspan="2">
<asp:LinkButton ID="CancelButton"
Text="Cancel"
CommandName="Cancel"
RunAt="server"/>
<asp:LinkButton ID="UpdateButton"
Text="Update"
CommandName="Update"
RunAt="server"/>
</td>
</tr>
<tr>
<td>
<asp:HiddenField ID="hdnSuccess" runat="server" />
<asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
</td>
</tr>
</table>
</EditItemTemplate>
</asp:FormView>
So in the .vb code , in the _Updated event handler I evaluate the value of #psiSuccess, if it is false (zero) display the error message (wich actually works) and keep the formview in EditMode, so the user has a chance of correcting the input.
Currently what is happening is that the error message is displayed but the FormView remains in ReadOnly mode (after the postback) so if the user has to change some input, they would have to click the "Update" button again and re-enter any information. When the update fails, all the data returns to the values currently in the database, so the user "loses" any changes they where trying to make.

aspnet web forms An item with the same key has already been added

I am using asp net 4.5.2 with model binding; I have a problem that whenever I try to use model binding on DropDownList It raises the error An item with the same key has already been added but if I change it to SQLDataSource the error goes away.
Thanks in advance
Update
Sample Code
<asp:ListView runat="server" ID="lvChairItem" DataKeyNames="ChairItemId" InsertItemPosition="FirstItem" OnItemCanceling="lv_ItemCanceling" OnItemUpdated="lv_ItemUpdated" OnItemEditing="lv_ItemEditing" ClientIDMode="AutoID" OnCallingDataMethods="ChairItem_CallingDataMethods" SelectMethod="GetByChairId" InsertMethod="InsertItem" UpdateMethod="UpdateItem" DeleteMethod="DeleteItem" ItemType="App.Model.ChairItem">
.............
<InsertItemTemplate>
<tr>
........
<td>
<asp:DropDownList ID="ddlRoomId" CssClass="" DataValueField="Value" DataTextField="Text" AppendDataBoundItems="true" Text='<%# BindItem.RoomId %>' Width="100%" OnCallingDataMethods="Room_CallingDataMethods" SelectMethod="GetAllForDDL" runat="server" EnableViewState="true">
<asp:ListItem Value="">--Select--</asp:ListItem>
</asp:DropDownList>
</td>
........
</tr>
</InsertItemTemplate>
.....................
</asp:ListView>
Then the issue is likely because you are populating it on page load without checking for Page.IsPostBack. You don't want to re-populate the controls on each postback. You do want to (often) allow ViewState. So I would re-enable, and wrap your populate method in (not page.ispostback).

DropDownList has a invalid SelectedValue Error

I'm doing this website for a school project, and when I run this website I have a GridView where I select one registry, then it opens the FormView with all the details about the selected registry
Image of the website working
Now, when I hit that Edit on the FormView it gives me the following error:
'ddl_SelectMae' has a invalid SelectedValue because it does not exist in the list of items. Parameter name: value
I know that, this error appears because the value on field "Mãe" is null, but I saw the database and that value can be null. (Same error applies to the "Pai" and "Comprador" field)
Here the part of the code where error happens, I can put all the code if needed
<asp:FormView ID="fv_Alteracoes" runat="server" DataKeyNames="idCao" DataSourceID="SqlDS_InsEdiDel">
<EditItemTemplate>
<table>
<tr>
<td>Mãe:</td>
<td>
<asp:DropDownList ID="dll_SelectMae" runat="server" DataSourceID="SqlDS_ListarMae" DataTextField="idCao" DataValueField="idCao"
SelectedValue='<%# Bind("Mae") %>'>
</asp:DropDownList>
<asp:SqlDataSource runat="server" ID="SqlDS_ListarMae" ConnectionString='<%$ ConnectionStrings:ConnectionString %>'
SelectCommand="SELECT [idCao], [Nome] FROM [tbl_Cao] WHERE ([Sexo] = 'F')">
</asp:SqlDataSource>
</td>
</table>
<asp:LinkButton runat="server" Text="Update" CommandName="Update" ID="UpdateButton" CausesValidation="True" />
<asp:LinkButton runat="server" Text="Cancel" CommandName="Cancel" ID="UpdateCancelButton" CausesValidation="False" />
</EditItemTemplate>
If I do the same but with a registry with all the details filled the website works 100% as I want
Image of website working perfectly
Can someone help me how to stop that error and keep the DropDownList to edit the fields?
PS: Sorry about my English but I am Portuguese, thank you for help
Change Your Data Source so that null can be allowed as :
SELECT [idCao], [Nome] FROM [tbl_Cao] WHERE ([Sexo] = 'F')
union
Select null,'None'

Required Field Validation not working in asp.net

I have required field validation control for a radiobutton list. So if no values are selected then it gives me a error which is fine. But when i redo select something and click the button then it does't not fires the server event of the button. Once i have the validation erro then whatever i do it disable the server side event.
any ideas why is it happening my code
<div id="studysub_popul" runat="server" visible="false">
<asp:Label ID="lbl_rdb_study_popul" runat="server"
CssClass="questions"
Text="2.Select your study subjects">
</asp:Label>
<asp:RadioButtonList ID="rdb_study_popul" runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="rdb_study_popul_SelectedIndexChanged">
<asp:ListItem>Individuals</asp:ListItem>
<asp:ListItem>Population</asp:ListItem>
</asp:RadioButtonList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server"
ControlToValidate="rdb_study_popul"
Display="Dynamic"
ErrorMessage="Study Subject is required"
ValidationGroup="StudySubject">
</asp:RequiredFieldValidator>
</div>
</td>
</tr>
<tr>
<td>
<asp:Button ID="btn_s_section" runat="server"
OnClick="btn_studysubject_section_Click"
Text="Next" ValidationGroup="StudySubject"
Visible="false" />
</td>
You should add a validating group to the RadioButtonList definition too.
<asp:RadioButtonList ID="rdb_study_popul" runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="rdb_study_popul_SelectedIndexChanged"
ValidationGroup="StudySubject">

ASP.NET - Required Field Validator giving false negative errors on Listbox

Background: I have a bundles listbox that inherits values from the carriers listbox once a carrier is selected via a web service.
I have a validationGroup on the button, I used Page.IsValid on the click handler and it says "Nothing".
When i select different carriers in IE8 it resets the other form values but not in IE9.
With Autopost=false on the lbCarriers, the Bundles listbox wont load any data.
With CausesValidation="true" in "lbCarriers", Bundles listbox wont load any data either Do you know how to do that w Ajax?
Do you know how I could do this w/ Ajax?
Problem: Using the required field validator on the bundles listbox is returning an a false erorr when I have bundles selected. When I click the Send Button, I get the "Select At Least 1 Bundle" Error Message but the invitation still sends out an i get an email.
Here's a screenshot of the application:
asp.net code on default.aspx page:
<tr>
<td class="style5">
Carrier:<br />
<font size="1">*Hold Ctrl Key Down to Select Multiple Carriers</font></td>
<td bgcolor="#ffffff" class="style7">
<asp:ListBox ID="lbCarriers" SelectionMode="Multiple" AutoPostBack="true"
runat="server" Height="86px" Width="250px" ValidationGroup="ValidationGroup">
</asp:ListBox>
</td>
<td bgcolor="#ffffff" class="style2">
<asp:RequiredFieldValidator ID="CarrierValidator" runat="server" Text="*"
ErrorMessage="Select At Least 1 Carrier" ControlToValidate="lbCarriers"
ValidationGroup = "ValidationGroup" ForeColor="Red" ></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style1">
Bundles:<br />
<font size="1">*Hold Ctrl Key Down to Select Multiple Bundles</font></td>
<td bgcolor="#ffffff" class="style6">
<asp:ListBox ID="bundles" SelectionMode="Multiple" runat="server" Height="86px"
Width="250px" Enabled="True"
ValidationGroup="ValidationGroup" CausesValidation="True">
</asp:ListBox>
</td>
<td bgcolor="#ffffff" class="style2">
<asp:RequiredFieldValidator ID="BundleValidator" runat="server" Text="*"
ErrorMessage="Select At Least 1 Bundle" ControlToValidate="bundles"
ValidationGroup = "ValidationGroup" ForeColor="Red" ></asp:RequiredFieldValidator>
</td>
</tr>
<asp:Button ID="Send_Button" runat="server"
Text="Send Invitation" ValidationGroup="ValidationGroup" Width="123px"/>
<br />
<asp:Label ID="Send_Success" runat="server" Text="Invitation sent!" Visible="false"></asp:Label>
<br />
<asp:ValidationSummary ID="ValidationSummary" runat="server" ForeColor="Red"
ValidationGroup="ValidationGroup" />
Question: What alternate code or work-around do you recommend for this issue?
Thanks for looking!
EDIT:
Add CausesValidation="true" in "lbCarriers"
I have removed Autopost="true" from first listbox i.e. "lbCarriers" and it is working now.

Resources