Label is not printing any value in ASP.NET using VB - asp.net

Need your expertise on the issue.
Background: I have a label control in the presentation layer which is purely used for status display. Status could be Update Fail Pass/Delete/Duplicate record etc. that is happening through GridView (refer Code 1).
The status in this label is shown using code behind procedure (refer Code 2)
Issue: The procedure is not displaying anything when called from UpdateTableRecordInDatabase(...) but it works when I hit the button (created test button to evaluate whether is there any issue in the code). I did the debug and the values are being passed successfully without any issues.
Code 1
<asp:Label ID="lblStatus" runat="server" visible="false"></asp:Label>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="TablesUpdatePanel" runat="server">
<ContentTemplate>
<asp:GridView ID="ListOfTables" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False"
DataKeyNames="PK_RestaurantTableID"
DataSourceID="DataSource1" Width="100%" CssClass="dataTable"
PageSize="15" ShowFooter="True" CellPadding="5"
CellSpacing="5" ShowHeaderWhenEmpty="True"
EmptyDataText="No records available in database"
OnRowUpdating = "UpdateTableRecordInDatabase"
OnRowDeleting="ListOfTables_RowDeleting">
<SortedAscendingHeaderStyle CssClass="sortasc" />
<SortedDescendingHeaderStyle CssClass="sortdesc" />
<columns>.....</columns>
</asp:GridView>
<asp:SQLDataSource .....>....</asp:SqlDataSource>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ListOfTables" />
</Triggers>
</asp:UpdatePanel>
</div>
Code 2
Protected Sub UpdateTableRecordInDatabase(sender As Object, e As GridViewUpdateEventArgs)
If CheckForDuplicateRecords(intAccountID, strTableName) = FALSE then
code here to update the table
else
e.Cancel = TRUE
Response.Redirect(Request.Url.AbsoluteUri)
PrintExceptionStatus("Table Names should be unique")
end if
End Sub
Sub PrintExceptionStatus(strMessage As String)
lblStatus.Visible = True
lblStatus.BackColor = Drawing.Color.LightYellow
lblStatus.ForeColor = Drawing.Color.Red
lblStatus.Text = "<img src='Images/error.png' align='absmiddle' hspace='5'>" + strMessage.ToString()
End Sub
Is there anything which I am overlooking or missing. Please guide.

Note that the GridView that fires the event is inside the UpdatePanel. Here is how it works - when the postback is triggered by something inside the UpdatePanel, the whole page life cycle is run, but then only the part of the page inside the UpdatePanel is updated on the client page.
So, after the GridView triggers the event, the text of the label is changed in the code behind (as you can see in debug), but since it is not inside the UpdatePanel the label is not changed, as you can see.
To solve the issue simply move the label inside the UpdatePanel - this make it a part of the HTML that is updated when postback inside UpdatePanel occurs:
<asp:UpdatePanel ID="TablesUpdatePanel" runat="server">
<ContentTemplate>
<asp:Label ID="lblStatus" runat="server" visible="false"></asp:Label>
Note that since it is inside the template, you might need FindControl now to access the label.

If you execute the UpdateTableRecordInDatabase the debugger goes in the if block or else block? If it goes in the else block you have written:
Response.Redirect(Request.Url.AbsoluteUri)
and after that you have called
PrintExceptionStatus("Table Names should be unique")
so in this case Page will be redirected to the given URL and if you have given URL as that of the current page it will definitely make the label to visible false as again the page load event will occur so try commenting Response.Redirect(Request.Url.AbsoluteUri)

Related

update panel webcontrol required form field

I created a simple control which uses an update panel with a button click trigger and yes a script manager above the control. Click the button and a label is updated with the current time and this has worked fine for 6 years
Today, I changed the page to be responsive with Bootstrap but this is irrelevant to this question.
The control was added to a page which has labels and textboxes (simple form with first name / last name).
<asp:TextBox ID="txtFirstName" runat="server" CssClass="form-control input-lg" Placeholder="Your First Name" MaxLength="20" Required="true"></asp:TextBox>
If I remove:
Required="true"
and click the button in the control the date / time updates but placing this back stops the date / time updating. I need to use both as I wish for the first name to be required but also for the time to update
Simple Example:
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="lblTime" runat="server" Text=""></asp:Label>
<asp:Button ID="btnRefreshTime" runat="server" Text="Refresh Time" OnClick="btnRefreshTime_Click" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnRefreshTime" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
Code Behind:
Protected Sub btnRefreshTime_Click(sender As Object, e As EventArgs)
lblTime.Text = DateTime.Now.ToString()
End Sub
What am I doing wrong and what would I need to do to resolve it without opening the form up to abuse (script attacks) etc? I don't wish to add the following to the page directive:
ValidateRequest="false"
Thank you in advance
Probabily the button server side event is prevented to execute due to the client side validation of required = "true".
Try to change the button with somewhat else which does not trigger client side validation by design. I would try with a LinkButton.

Losing update panel trigger from databound gridview in tab container

I'm having some trouble getting a command link in a gridview to maintain it's ability to change tabs after the initial postback. So below you will see the structure of my content (heavily simplified):
<ajaxToolkit:TabContainer runat="server" ID="tabBody">
<ajaxToolkit:TabPanel runat="server" ID="tabPanel1">
<ContentTemplate>
<asp:UpdatePanel runat="server" ID="updPanel1">
<ContentTemplate>
<asp:Gridview runat="server" ID="grd1" OnRowCommand="grd1_RowCommand" OnRowDataBound="grd1_RowDataBound">
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkChangePanels" runat="server" CommandArgument='<%#Eval("id") %>' CommandName="gotopanel2" Text='<%#Eval("FirstName") & " " & Eval("LastName")%>' />
</ItemTemplate>
</asp:TemplateField>
</asp:Gridview>
</ContentTemplate>
</asp:UpdatePanel>
</ContentTemplate>
</ajaxToolkit:TabPanel>
<ajaxToolkit:TabPanel runat="server" ID="tabPanel2">
<ContentTemplate>
<asp:UpdatePanel runat="server" ID="updPanel2">
<ContentTemplate>
<asp:Gridview runat="server" ID="grd2">
</asp:Gridview>
</ContentTemplate>
</asp:UpdatePanel>
</ContentTemplate>
</ajaxToolkit:TabPanel>
</ajaxToolkit:TabContainer>
In order to fill the gridview on panel 1, there is a search box which the user types into and I call a function to bind a linq query to it.
Now I add the rowcommand as a postback trigger on rowdatabound:
Protected Sub grd1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim lb As LinkButton = CType(e.Row.FindControl("lnkChangePanels"), LinkButton)
If Not lb Is Nothing Then
ToolkitScriptManager1.RegisterPostBackControl(lb)
End If
End If
End Sub
Then here is the code I have to trigger the tab panel to change (and do some other stuff):
Protected Sub grd1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles grd1.RowCommand
Dim id = e.CommandArgument.ToString()
Select Case e.CommandName
Case "gotopanel2"
eventDetails(id, "C")
tabBody.ActiveTab = tabPanel2
End Select
End Sub
This causes a proper postback and changes the tab, everything works as intended. But if I go back to the first tab and try clicking another row in gridview 1, nothing happens.
Is there a way to structure this so the that either the tab can change without losing the postback trigger or am I going about this all wrong?
Thanks.
Postback trigger is not lost. Problem is caused by individual UpdatePanels in each tab.
Put entire TabContainer within UpdatePanel and you can remove UpdatePanels from tabs (but you don't have to). Make sure that UpdateMode of that new panel is set to "Always".
I think the reason why it does not change in your example is that UpdatePanel only refreshes it's own content and attribute that decides if tab is visible or not is set for div (tabPanel) outside that UpdatePanel. When you go back to tab with grid you do it client-side by clicking on it and that's when it goes wrong.
To get to the bottom of the problem and figure out why it does work during the first postback you would probably have to debug ajax toolkit javascript for TabContainer control.

updatepanel - making other control on page visible or invisible

I'm using a update panel to display some results on a page and it is working fine with no probs.
If though no results were returned I would like a message to display - saying no records found.
The trouble is getting the asp:panel(pnlNoUsers) visible option to be true or false(which contains the no records found message is the prob I'm having
My code for for the update panel is:
<asp:UpdatePanel ID="pnlCust" runat="server">
<ContentTemplate>
<asp:Panel ID="pnlNoUsers" runat="server" visible="false">
<div class="inner-page-title">
<h2>
No records found.</h2>
</div>
</asp:Panel>
<%=show_cust()%>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnRefresh" />
</Triggers>
</asp:UpdatePanel>
The show_cust() function simply returns a string which will be displayed on the page:
If bHasUsers = False Then
pnlNoUsers.Visible = True
Return ""
End If
pnlNoUsers.Visible = False
Return strUsers & "</ul>"
The panel "pnlNoUsers"visibility property isn;t changing at all?
Anyone know how I can do this?
Thanks,
I don't know the complexity of your requirement but you can skip the conditional logic altogether by using a data control. You can use a gridview control which has an
EmptyDataText property that you can use.
MSDN: Gridview EmptyDataText property
You can manually bind the gridview control with data using DataSource & dataBind properties.
Without your button click event, it is difficult to determine where you might be going wrong. A couple ideas though: Set UpdateMode to Conditional, this is a normal mode to have update panels in, get rid of your inline response write, that is not a good way to handle ASP.NET data display, and add a Literal tag that you can render the user's list. As Damien mentioned, I would use a ListView, Repeater, or GridView (in that order) to render your user list rather than generating an unordered list in code and writing it to the browser.
<asp:UpdatePanel ID="pnlCust" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Panel ID="pnlNoUsers" runat="server" Visible="false">
<div class="inner-page-title">
<h2>No records found.</h2>
</div>
</asp:Panel>
<asp:Literal ID="CustomerListLiteral" runat="server" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnRefresh" />
</Triggers>
</asp:UpdatePanel>
<asp:Button ID="btnRefresh" runat="server" OnClick="btnRefresh_Click" />
Handle your update panel efforts in a button click event. My bet is that the response write you had inline was not triggering the update panel to work. This should do what you want.
Protected Sub btnRefresh_Click(sender As Object, e As EventArgs)
Dim bHasUsers As Boolean = False
Dim strUsers As String = String.Empty
If bHasUsers = False Then
pnlNoUsers.Visible = True
Else
pnlNoUsers.Visible = False
CustomerListLiteral.Text = strUsers & "</ul>"
End If
' Force an update refresh if necessary, but this shouldn't be needed
pnlCust.Update()
End Sub
Why you are using the function show_cust(). You can add the functionality in the button click action. because initially the panel is not visible. it need to to be visible while button click ccording to the condition. So add the functioality
`
If bHasUsers = False Then
pnlNoUsers.Visible = True
Return ""
End If
pnlNoUsers.Visible = False
Return strUsers & "</ul>"
on btnRefresh click event. It will work

RadioButtonList inside UpdatePanel inside Repeater, Can I?

I have a repeater with a RadioButtonList inside the ItemTemplate, but when the RadioButtonList.OnSelectedIndexChanged event fires it generates a full postback. What have I done wrong in my code below? How can I get the OnSelectedIndexChanged to generate an Async Postback?
<asp:UpdatePanel runat="server" ID="UpdatePanel2">
<ContentTemplate>
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="sqlOptions">
<ItemTemplate>
<asp:UpdatePanel runat="server" ID="pnlA">
<ContentTemplate>
<strong>
<%# Eval("Name") %></strong><br />
<asp:RadioButtonList ID="RadioButtonList1"
DataSourceID="sqlOptionValues" runat="server"
DataTextField="id" DataValueField="Id" AutoPostBack="true"
OnSelectedIndexChanged="LoadPrice"
ValidationGroup="options" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
ForeColor="Red" runat="server"
ControlToValidate="RadioButtonList1"
ErrorMessage="Required Field"
ValidationGroup="options" />
<asp:SqlDataSource ID="sqlOptionValues" runat="server"
ConnectionString="<%$ ConnectionStrings:
ConnectionString6 %>"
SelectCommand='<%# "SELECT DISTINCT OptionValue.Name,
OptionValue.Id FROM CombinationDetail
INNER JOIN OptionValue
ON CombinationDetail.OptionValueId = OptionValue.Id
WHERE (OptionValue.OptionId =" +
Eval("Id") + ")" %>'>
</asp:SqlDataSource>
<br />
</ContentTemplate>
</asp:UpdatePanel>
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
Many thanks for any help :)
This is a real-world use case. I have a page with Repeaters, Ajax Accordions inside of other Accordions, Update Panels inside other Update panels, you name it. The page works great, except when I want to update one of the Accordion panels with my RadioButtonList (RBL). Even with the RBL inside an update panel, it causes a postback of the entire page. I tried everything. I finally realized it wasn't me when I noticed my buttons would work just fine. I figure it must be a bug in either the framework or the Ajax Control Toolkit. I did find people reference this link all over the web (http://blog.smarx.com/posts/the-case-of-the-radiobuttonlist-half-trigger.aspx), but this link from 2007 is dead now and probably no longer applicable, so that's no help.
What I ended up doing was going with what works - that submit button. All I did was add an onclick attribute to the RBL to call a hidden button. Now you don't want to set the button to Visible=false because then the button won't appear in the generated markup. Instead, set the button's style to display:none; so that no one will see this hack, because yes, that's what this workaround is - it's a hack, but simple and just as effective as what you'd expect. Don't forget to remove the Autopostback="True" from your RBL.
CAVEAT: Because I'm using a hacked button for the onclick event, it's possible for the user to click in the area of the RBL, but not actually select an item. When this happens, our onclick triggers an AsyncPostBack and the codebehind logic will be processed, so please keep that in mind. To give you an idea of what I mean: all the Page_Load() events will be called, but rbl_Questions_SelectedIndexChanged() won't be if they happen to click in the area of the RBL without actually selecting an item. For my purposes this causes no issues in my logic and has no effect on the user.
Here's the Code:
Somewhere In the .Aspx Page:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:RadioButtonList ID="rbl_Questions" runat="server"
OnSelectedIndexChanged="rbl_Questions_SelectedIndexChanged">
</asp:RadioButtonList>
<asp:Button ID="btn_rbl_Questions" runat="server" style="display:none;"/>
<asp:Label ID="lbl_Result" runat="server" Text="" Visible="false">
</asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
In the Page_Load() event:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
//Instead of using the AutoPostback of the RBL, use this instead.
rbl_Questions.Attributes.Add("onclick",
"document.getElementById('"
+ btn_rbl_Questions.ClientID
+ "').click();");
//Bind your RBL to a DataSource, add items programmatically,
// or add them in the aspx markup.
}
}
In the rbl_Questions_SelectedIndexChanged() event:
protected void rbl_Questions_SelectedIndexChanged(object sender, EventArgs e)
{
//Your code here.
//My code unhid the lbl_Result control and set its text value.
}
Update 05/24/2011
The above "hack" is no longer necessary (I am leaving it above since this was marked as the answer by the author). I have found the best way to do this, thanks to this SO Answer:
Updatepanel gives full postback instead of asyncpostback
The code is much simpler now, just remove what I put in the Page_Load() method and remove the Button I used in the Aspx page and add ClientIDMode="AutoID" and AutoPostBack="True" to the control you want the UpdatePanel to capture.
Somewhere In the .Aspx Page:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:RadioButtonList ID="rbl_Questions" runat="server"
ClientIDMode="AutoID" AutoPostBack="true"
OnSelectedIndexChanged="rbl_Questions_SelectedIndexChanged">
</asp:RadioButtonList>
<asp:Label ID="lbl_Result" runat="server" Text="" Visible="false">
</asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
MS changed how ClientID's are generated in .net 4.0 from "AutoID" to "Predictable" and I guess the ScriptManager or UpdatePanel's weren't updated correctly to use it. I can't find documentation on why that is anywhere or if it was left that way by design.
I seriously don't miss winforms.
Try this:
<asp:UpdatePanel runat="server" UpdateMode="Conditional" ID="pnlA">
You'll also need to setup
<Triggers>
//radio buttons
</Triggers>
Not sure how you'll do that since it's a dynamically built list.

Default radio button not triggering an UpdateControl postback

I have three radio buttons on a form - A, B, C. Each of these selections populates a dropdown list with data specific to the option. When the form loads, I set option A to be checked (as the default).
When I select buttons B or C, the AsyncPostBack triggers fine and the dropdown is populated. BUT, subsequently selecting A from either B or C does not trigger the event.
I suspect that because A was checked when the form loaded, the browser is not seeing any "change" to raise the event.
So what can be done to enable the default A button recognise it is being changed from B or C in order to raise the postback?
I have tried both setting the checked state of button A in code on inital loading of the page only (ie IsPostBack is False) and alternatively setting the checked attribute of the radiobutton in the html, with the same results. If I don't default the radio button the functionality works as expected, except I don't have the radio button and dropdown list defaulted when the page first loads.
The html...
<asp:RadioButton ID="radBook" runat="server" AutoPostBack="true" GroupName="grpArticleType" Text="Book" />
<asp:RadioButton ID="radCD" runat="server" AutoPostBack="true" GroupName="grpArticleType" Text="CD" />
<asp:RadioButton ID="radDVD" runat="server" AutoPostBack="true" GroupName="grpArticleType" Text="DVD" />
<asp:UpdatePanel ID="pnlTasks" runat="server" UpdateMode="Conditional" RenderMode="Inline">
<ContentTemplate>
<asp:DropDownList ID="dropShippingSize" runat="server" CssClass="dropdownMandatory"></asp:DropDownList>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="radBook" />
<asp:AsyncPostBackTrigger ControlID="radCD" />
<asp:AsyncPostBackTrigger ControlID="radDVD" />
</Triggers>
</asp:UpdatePanel>
The code behind...
Sub Page_Load
If Not Me.IsPostBack Then
radBook.Checked = True
End If
End Sub
Private Sub rad_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles radBook.CheckedChanged, radCD.CheckedChanged, radDVD.CheckedChanged
zLoadShippingSizeDropdown()
End Sub
I had the same problem and looked for an answer for hours. This seems to have nothing to do with ViewState or anything similar, but with some kind of incompatibility of using a pre-checked RadioButton as trigger for an Async PostBack.
The work around I found is amazingly easy and worked right away; instead of using the checked=true on the mark-up or myRadioButton.Checked on the server side, I did the following:
Not setting the attribute on Mark-up and add this on the Page_Load event:
if (!IsPostBack)
{
MyRadioButton.InputAttributes["checked"] = "true";
...
}
I hope this helps and saves some people hours of hair pulling :)
I'm guessing you need to need to check if the page is a postback in your load event:
protected void Form_Load(object sender, EventArgs e)
{
if (!Page.IsPostback)
{
// Set radiobutton A...
}
}
We had the same problem and it seems you will have to set the other "checked" property for radio buttons to "false".
So please add the lines
radCD.Checked = False
radDVD.Checked = False
Are you by chance handling viewstate in your code behind as well? If so then you need to handle the AJAX version of it as viewstate can often be lost on AJAX style pages. Try putting your buttons inside the update panel and see if you get the same behaviour if the panel has it's update mode set to conditional. Don't worry about the postback triggers if you do that.
The asynch triggers are only for items inside an update panel. any item outside of a panel will doa full postback by design.
<asp:UpdatePanel ID="pnlTasks" runat="server" UpdateMode="Conditional" RenderMode="Inline">
<ContentTemplate>
<asp:RadioButton ID="radBook" runat="server" AutoPostBack="true" GroupName="grpArticleType" Text="Book" />
<asp:RadioButton ID="radCD" runat="server" AutoPostBack="true" GroupName="grpArticleType" Text="CD" /><asp:RadioButton ID="radDVD" runat="server" AutoPostBack="true" GroupName="grpArticleType" Text="DVD" />
<asp:DropDownList ID="dropShippingSize" runat="server" CssClass="dropdownMandatory">
</asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
WOW, I would have never thought that could be the bug. Saved many hours of frustration.
Thanks Juan going through the carppy Microsoft issue and found a solution for the rest.

Resources