Dropdownlist looses value during autopostback - asp.net

I have a couple of straightforward dropdownlists. The first is bound by a linqdatsource in the html with autopostback set to true. The selection of the first determines the data in the second. When I select an item in the first, the selectedindexChanged event fires; however, the selected value is always the first item in the list and the list then re-binds and reverts to its default state. Do I have to bind it in code-behind to prevent this?
<asp:DropDownList ID="dd_shirtcolor" runat="server" AppendDataBoundItems="true" AutoPostBack="True">
<asp:ListItem Text="Select Color" />
</asp:DropDownList>
<asp:LinqDataSource ID="LinqDataSource1" runat="server"
ContextTypeName="IPC.IPCDataDataContext" EntityTypeName=""
TableName="Shirts" Where="IsActive == #IsActive">
<WhereParameters>
<asp:Parameter DefaultValue="true" Name="IsActive" Type="Boolean" />
</WhereParameters>
</asp:LinqDataSource>

Make sure you have ViewState enabled so it can populate the list before it "selects" the item.
Also, make sure you don't repopulate in Page_Load and lose the selected value.
eg.
if (!IsPostback) { // Populate }

Some alternatives to managing cascading drop down lists yourself are:
ASP.NET AJAX Control Toolkit:
ASP.NET AJAX Cascading Drop Down
Cascading Drop Down Using ASP.NET and jQuery:
Cascading Drop Down Using ASP.NET And jQuery

I was able to work around this problem by binding the dropdown in the code behind in page_init method with the proper !postback conditional instead of using the linqdatasource to bind it. I am still not sure what was causing it however.

Related

disable comboboxlist with a click of a radiobutton asp.net

Am trying to disable my comboboxlist when I press a specific selection from my radiobutton list, or re-enable the comboboxlist If I make a different selection from radiobuttonlist.
Am using postpacks in my asp as well, but am I cant find how to make this work.
When I double click the radiobutton list and I get the automatic method generation.
I don't know what kind of attributes should I use to make the radiobuttons work when changed. I tried a few combinations but none seems to work. Any ideas?
use AutoPostBack="true" property as follow
<asp:DropDownList ID="MyDropDown" runat="server" AutoPostBack="true"
onselectedindexchanged="MyDropDown_SelectedIndexChanged">
and
<asp:RadioButtonList id="docList" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="loginUser" />

entitydatasource value retrieval

I have an entitydatasource defined in the markup as so
<asp:EntityDataSource ID="edsFV" runat="server"></asp:EntityDataSource>
<asp:EntityDataSource ID="eds_fv_singleuserprofile" runat="server"
ConnectionString="name=webEntities" DefaultContainerName="webEntities"
EnableFlattening="False" EnableUpdate="True" EntitySetName="userprofiles"
Where="it.ASPUserId = #SelectedValue" >
<WhereParameters>
<asp:Parameter DefaultValue="20" Name="SelectedValue" Type="Int32" />
</WhereParameters>
</asp:EntityDataSource>
I it requeries for information on a dropdown selection. It returns a single item with 5 properties. I am trying to acces one of the properties, "FullName" to use in the legend of the fieldset within the update panel this dropdown is changing data for as follows;
<asp:UpdatePanel ID="udpUserProfile" runat="server" >
<ContentTemplate>
<fieldset id="singleuserprofile" >
<legend>Profile details for <%# I want to databind the "FullName" property value here%></legend>
"other code"
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>
I cannot seem to find the method that works properly to do so. Any help appreciated.
While I haven't found anything explicitly stating so, it is my understanding that Data Sources are used solely to interface with data-bound controls. From the MSDN page:
Data source controls greatly expand the capabilities of data-bound
controls such as the GridView, FormView, and DetailsView controls. By
working together, data source controls and data-bound controls let you
retrieve, modify, page, sort, and filter data from different data
sources with little or no code.
You should probably get the data for the fieldset tag with an Entity query, and use the entitydatasource with your DetailsView only.
As best I can understand, you are using a DropDownList with AutoPostBack to select the item in the DetailsView. If, as your comment implies, the DetailsView is not updating when you do the partial postback you should call a .DataBind() on the control. Also, using a ControlParameter instead of a basic Parameter may be more appropriate in this context.

ASP.NET DropDownList not getting correct SelectedItem

We are using ASP.NET for one of our projects. However, when we are trying to read the SelectedItem or SelectedValue property of the DropDownList we are using in the callback function of a Link click, we are not getting the correct SelectedItem.
<FooterTemplate>
<asp:DropDownList ID="cmbTesters" ClientIDMode="Static" runat="server" Width="300px" DataSource='<%# PopulateTesterNames() %>' DataTextField="FullName" DataValueField = "PK_ID"></asp:DropDownList>
</FooterTemplate>
This is the DropDownList in the aspx file. The drop down is present within a GridView's Footer Row. We are invoking the following set of code on clicking a link.
if (int.TryParse(((DropDownList)dgCreateCPRVerificationResponse.FooterRow.FindControl("cmbTesters")).SelectedValue, out TesterID))
{
TesterID = int.Parse(((DropDownList)dgCreateCPRVerificationResponse.FooterRow.FindControl("cmbTesters")).SelectedValue);
}
The problem we are facing is that whatever value we choose, the SelectedValue is always of the first item in the list. We are using REST based URL defined in the global.asax file. Also note that this is not built on any framework.
Please help as soon as possible
Make sure to put the binding methods of the dropdownlist and the gridview inside if (!IsPostBack)

Automatically rebind controls on ASP.NET postback

Is there a flag or property value I can set to have my controls re-bind on every page load, instead of just the initial one? I'm still very new to ASP.NET, so I would like to do it properly (if such a way exists) before resorting to the first thing that "works".
I am working on a simple WebForms page, which boils down to a few SQLDataSource-bound Repeaters; for example:
<asp:Repeater ID="ExampleRepeater" runat="server" DataSourceID="ExampleDataSource"
OnItemDataBound="ExampleRepeater_ItemDataBound">
<ItemTemplate>
<asp:Label ID="DataboundControlID" runat="server" Text='<%# Eval("ExampleColumnName")%>' />
</ItemTemplate>
</asp:Repeater>
<asp:SqlDataSource ID="ExampleDataSource" runat="server" ConnectionString="example_connection_string"
SelectCommand="ExampleStoredProcedure" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter DefaultValue="exampleValue" Name="parameter1" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
After the user has interacted with my page, they can initiate a postback which will change the state of the database. I'd like the postback'ed page to reflect the changes to the database. Please let me know if I can clarify my situation any further.
After your processing i.e. updating database you can re-bind the Repeater by calling DataBind method like:
ExampleRepeater.DataBind();
In my experience, some controls do, others don't. E.g. the standard ASP.NET controls from Microsoft always worked for me automatically, whereas the ASPxGridView from DevExpress needs a manual rebind on every postback/callback.

What do you suspect when ASP.NET ignores a CustomValidator?

This is as much a code maintenance issue as a code issue, but I have a WebForm that no longer checks it CustomValidator. It worked when I last touched the code over a year ago, but it no longer works now that the user has requested some changes ...
The WebForm contains a data-bound drop down with a default " - All -" item with String.Empty as its value. When the user clicks the submit button, the validator should check that the drop down's value is not String.Empty. I've set break points in the client validation code and the server validation code, but neither fire.
Where would you start looking? What are the usual suspects? I have, of course, compared my working copy to what is in source control, but nothing jumps out as being suspicious.
Just in case it matters, here is my code:
<asp:DropDownList ID="_AssessmentDropDown" runat="server" DataSourceID="_AssessmentsData" CausesValidation="true" AutoPostBack="false"
DataTextField="AssessmentName" DataValueField="AssessmentName" OnDataBound="_HandleAssessmentsBound">
</asp:DropDownList>
<asp:CustomValidator ID="_AssessmentValidator" runat="server" ClientValidationFunction="_HandleValidateAssessment_Client"
ControlToValidate="_AssessmentDropDown" ErrorMessage="* You must select an Assessment."
OnServerValidate="_HandleValidateAssessment" />
<asp:ObjectDataSource ID="_AssessmentsData" runat="server"
OldValuesParameterFormatString="original_{0}" SelectMethod="GetData"
TypeName="DataTableAdapters.GET_GRADE_ASSESSMENTSTableAdapter">
<SelectParameters>
<asp:ControlParameter Name="GRADECODE" ControlID="_GradeCodeDropDown" PropertyName="SelectedValue" />
</SelectParameters>
</asp:ObjectDataSource>
I notice a couple of issues
I don't think you need a CausesValidation=true if AutoPostBack is set to false
You do not use validation groups, so that cannot be the cause
Why not use a RequiredFieldValidator?
If you want to fire validation on empty fields, set the ValidateEmptyText property to true
A CustomValidator doesn't fire if the control it is validating has an empty value, so a CustomValidator should always be accompanied by RequiredFieldValidator
Some troubleshooting steps:
Is this the only validator on the form?
Is validation enabled on the page?
Is validation enabled for the targeted control?
Is the validator itself enabled?
I would take a serious look at the ValidationGroup.
If something has been left out of the group, it wouldn't validate anymore. Otherwise, make sure that you don't have any javascript error (for the client side) and that the method that is "OnServerValidate" has a break point inside.
Is the validator in the same validator group as the submit button?

Resources