Automatically rebind controls on ASP.NET postback - asp.net

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.

Related

Label value read for Insert command is not the value shown in browser

Good afternoon.
I have a simple gridview with a field like this:
<asp:TemplateField HeaderText="USD Full Load Machine">
<ItemTemplate>
<asp:Label ID="lblUSDFullLoad" runat="server" Text='<%# Bind("USDFullyLoadMachine") %>' />
</ItemTemplate>
</asp:TemplateField>
The InsertCommand and Insertparameters are set up like this:
<asp:SqlDataSource (code omitted)
InsertCommand="Insert Into [xxxxTable]
([SubmissionID],USDFullyLoadMachine]) Values(#newSubID,#usdflm)">
<InsertParameters>
<asp:ControlParameter Name="newSubID" ControlID="lblNewSubmissionID" />
<asp:ControlParameter Name="usdflm" ControlID="gridConversionTotals$ctl02$lblUSDFullLoad" />
</InsertParameters>
</asp:SqlDataSource>
When I change the gridConversionTotals$ctl02$lblUSDFullLoad label's text using client-side javascript, and I execute the insert method on the sql datasource control in code behind, the value sent to SQL is NOT the new value of the label, i.e. is not the value shown on the browser, it is the value the label had when it was last databound.
I initially thought that this was because the server, upon executing the insert command, could not possibly know what the client was showing, but then this is not true, because if I change the label to a textbox and leave all the code intact, the value sent to the database is indeed the one shown on the client.
Can someone please explain why the insert method, in this instance, treats a label's and a textbox's client-side content differently?
And does this mean that generally when I want to change values client-side and then send them to the database I will need to always use textboxes?
Thank you.
After some further research I found this post https://stackoverflow.com/a/10324721/1266732, which explains that the label will not post the value back to the webserver, and therefore it is recommended to use textboxes and styling them as labels for this purpose.
At a technical level, form values are sent using <input /> elements or cookies. If your javascript is not editing an <input /> element or a cookie (or in some way modifying a GET URL), then your value will not make it to the server.

Put SQL and ASP code on a script instead of on my web page

Im designing a web site and trying some new concepts. instead of just coding everything onto a web page, i am populating different areas of the page using a database. for example on a news page, i have a drop down to select the story, then I have different areas of the page pull in the headline, story, picture and date which are all stored in the database. everything is working good. the only thing I want to do is clean up the code a little. Id like for all the connection strings and select statements to be stored in a method on a script or something. and preferably on a HTML page, not an aspx page.
I have a decent amount of knowledge with basic HTML, and some experience programming with Visual Basic.net and SQL. I am using Visual studio 2012, putting all of this on an ASPX page.
here is an axample of what i have written and working. this displays the headline of the story based off of the value selected in the "NewsDropDown" Drop list.
<%-- displays the headline --%>
<asp:FormView ID="NewsHeadlineText" runat="server"
DataSourceID="NewsHeadline" class="hdr"
meta:resourcekey="NewsHeadlineTextResource1" >
<ItemTemplate>
<asp:Label ID="HeadlineLabel" runat="server"
Text='<%# Bind("Headline") %>' meta:resourcekey="HeadlineLabelResource1" />
<br />
</ItemTemplate>
</asp:FormView>
<asp:SqlDataSource ID="NewsHeadline" runat="server"
ConnectionString="<%$ ConnectionStrings:VBallTalksDBConnectionString %>"
ProviderName="<%$ ConnectionStrings:VBallTalksDBConnectionString.ProviderName %>"
SelectCommand="SELECT [Headline] FROM [News] WHERE ([Headline] = ?)">
<SelectParameters>
<asp:ControlParameter ControlID="NewsDropDown" Name="Headline"
PropertyName="SelectedValue" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
You can use jQuery's AJAX or a regular AJAX for querying your script that touches the DB in ASP and return the results of the processing in JSON. That way when it comes back you can continue to populate the sections of your website in the programming language of your choice. In PHP with MySQL using AJAX/Javascript and HTML5/CSS3 I have done this in the past with much success, let me know if you have an static mockup in JSFiddle (http://jsfiddle.net/) or JSBin if you decide to use Javascript to address your needs

I'm trying to pull a control parameter for a sql datasource from a dropdown but it's not being recognized

I have 2 sql datasources. What's supposed to happen is the following: On page load, the first sql datasource pulls a list of 'desknames' and populates a dropdown. It should default to the first deskname but I added some c# code behind to select the first item by index on pageload just to be safe. Then a second sql datasource should load, using the selected 'deskname' as a control parameter. From the second sql datasource I populate an html table with labels that are populated in the code behind from the datasource. I've tested the second datasource-html table when I manually put in the control parameter, and it works fine.
All I can think of is that somehow the deskname in the dropdown is not being selected in time to be passed as a parameter to the second sql datasource, but I don't know how to fix it. I've tried playing around with the order that things appear in the code, but it hasn't made a difference. By the way I'm using asp.net webforms with c#
Here is my code:
<asp:HiddenField ID="hiddenUserID" runat="server" Value="" />
<asp:SqlDataSource ID="Desknames" runat="server"
ConnectionString="<%$ ConnectionStrings:spvConnectionString %>"
SelectCommand="exec pmtv2.spTOOL_Deskdropdown #username">
<SelectParameters>
<asp:ControlParameter ControlID="hiddenUserID" Name="username" PropertyName="value" />
</SelectParameters>
</asp:SqlDataSource>
<div id="topdiv" style="float:left; padding-left:2.5%; width:30%; border-bottom:0px; height:20%;">
<h2>
<asp:DropDownList ID="ChooseDesk" runat="server" DataSourceID="Desknames"
DataTextField="Deskname" DataValueField="Deskname" AutoPostBack="true" class="dropdown" OnDataBound="ChooseDesk_databound">
</asp:DropDownList>
</h2>
<asp:SqlDataSource ID="DeskSummary" runat="server"
ConnectionString="<%$ ConnectionStrings:spvConnectionString %>"
SelectCommand="exec pmtv2.spTOOL_LandingPageDesk #username, #Deskname">
<SelectParameters>
<asp:ControlParameter ControlID="hiddenUserID" Name="username" PropertyName="value" />
<asp:ControlParameter ControlID="ChooseDesk" Name="Deskname" PropertyName="SelectedValue" DefaultValue="Laundry & Tobacco"/>
</SelectParameters>
</asp:SqlDataSource>
Notice I have defaultvalue="laundry & tobacco", this is just a temp fix that allows the second sql datasource to populate but normally I won't be able to hard code in a default value like this.
This might be a tricky one, but any suggestions on why this is not working would be greatly appreciated.
Thanks!
Change your SeletCommand to
SelectCommand="spTOOL_LandingPageDesk"
and add the following attribute
SelectCommandType="StoredProcedure"
if your parameters are already defined in your stored procedure you don't have to declare them again by using the exec call.
I'm assuming your pmtv2 is the user you are using to log into the database. You don't need that as the connection string in the web.config has already taken care of this for you.
Also, I noticed your using class in your drop down's attributes. Set that to CssClass. It may be contributing to your problem.
class="dropdown"
should be:
CssClass="dropdown"
I've discovered that you need to initialize the control. I would recommend using an OnInit event and an OnSelecting in the datasource. In these functions I would set your control values.

Is it possible to use a control in a different content tag as a parameter?

I currently have two Web Controls, one being a CheckBoxList, and the other a GridView. The GridView's data configuration has a parameter in it's query which is linked to the selected values from the CheckBoxList. However, when the two controls are in separate content tags like so:
<asp:Content ID="ListPanel" runat="server" ContentPlaceHolderID="LeftContent">
<h3>Pick Info Here</h3>
<asp:CheckBoxList ID="cbList1" runat="server"
DataSourceID="TestDataSource"
DataTextField="St" DataValueField="St" RepeatColumns="2">
</asp:CheckBoxList>
</asp:Content>
<asp:Content ID="ResultsPanel" runat="server" ContentPlaceHolderID="RightContent">
<asp:GridView ID="gView1" runat="server"
AllowPaging="True" AllowSorting="True"
AutoGenerateColumns="False" DataSourceID="TestDS1">
<Columns>
...
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="TestDS1" runat="server"
...
SelectCommand="SELECT ST FROM [Table] where ST = ?">
<SelectParameters>
<asp:ControlParameter ControlID="cbList1" Name="?"
PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
</asp:Content>
It works fine when I put both controls in the same <asp:Content> tag, but things call apart with an error of System.InvalidOperationException: Could not find control 'cbList1' in ControlParameter '?'. Is there a way to keep the controls separate, or do they have to be inside the same content tag?
Seems a little krufty but you could put a HiddenControl in the ResultPanel and then set it's value to that of cbList1.SelectedValue on page load.
I know you can access controls regardless of the Content they are in, from code behind but apparently you can't from within the Content itself on the aspx side.
Apparently this can be done by prefixing the ContentPlaceHolderID to the ControlID of the parameter entry. In my case, the code would be:
SelectParameters>
<asp:ControlParameter ControlID="LeftContent:cbList1" Name="?"
PropertyName="SelectedValue" />
</SelectParameters>
since the Control the parameter reads from is in the LeftContent tag.
Some years later... I had the same problem with a gridview and a control parameter. In the source-code of the rendered page, you can find the exact "path" to the element. In my case it was not only gv1$txtEmployeeName, but gv1$ctl02$txtEmplyeeName.
I guess, ctl02 means EditItemTemplate, because including ctl02$ solved my problem.

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