"Inline" function call: function is never hit - asp.net

I'm trying to make a tabbed menu for the asp.net website I'm working on. One of the pre-requisite is obviously to color the current tab differently, so the user can know on which tab is currently is.
To do this, I made this method in my code-behind:
Protected Function GetCssClass(ByVal ctrl As LinkButton) As String
If ctrl.ID = currentLink Then
Return "current"
Else
Return String.Empty
End If
End Function
and I call the method like this in my aspx page:
<asp:LinkButton ID="LinkButton1" runat="server" PostBackUrl="/Default.aspx" CssClass="<%#GetCssClass(LinkButton1) %>" >Home</asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" PostBackUrl="/Directory/page1.aspx" CssClass="<%#GetCssClass(LinkButton2) %>" >Page1</asp:LinkButton>
But the method is never hit... As I understand, the method should be called each time the LinkButton is drawn...
Does someone have an idea why?
Thanks in advance !
Edit: Just as a precision, all this code is in the masterpage.
Edit2: Here are the changes I made according to Quagland's suggestion.
In the aspx masterpage:
<asp:HiddenField ID="currentLink" runat="server" />
<asp:LinkButton ID="LinkButton1" runat="server" PostBackUrl="/Default.aspx" OnClick="LinkButton_Click" OnPreRender="LinkButton_PreRender" >Home</asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" PostBackUrl="/OtherDirectory/Page1.aspx" OnClick="LinkButton_Click" OnPreRender="LinkButton_PreRender" >Page1</asp:LinkButton>
<asp:LinkButton ID="LinkButton3" runat="server" PostBackUrl="/OtherDirectory/Page2.aspx" OnClick="LinkButton_Click" OnPreRender="LinkButton_PreRender" >Page2</asp:LinkButton>
<asp:LinkButton ID="LinkButton4" runat="server" PostBackUrl="/OtherDirectory/Page3.aspx" OnClick="LinkButton_Click" OnPreRender="LinkButton_PreRender" >Page3</asp:LinkButton>
And in the code behind:
Protected Sub LinkButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles LinkButton1.Click, LinkButton2.Click, LinkButton3.Click, LinkButton4.Click, LinkButton5.Click, LinkButton6.Click, LinkButton7.Click, LinkButton8.Click
Dim lnk As LinkButton = CType(sender, LinkButton)
currentLink.Value = lnk.ID
End Sub
Protected Function GetCssClass(ByVal ctrl As LinkButton) As String
If ctrl.ID = currentLink.Value Then
Return "current"
Else
Return String.Empty
End If
End Function
Protected Sub LinkButton_PreRender(ByVal sender As Object, ByVal e As EventArgs) Handles LinkButton1.PreRender, LinkButton2.PreRender, LinkButton3.PreRender, LinkButton4.PreRender, LinkButton5.PreRender, LinkButton6.PreRender, LinkButton7.PreRender, LinkButton8.PreRender
Dim lnk As LinkButton = CType(sender, LinkButton)
lnk.CssClass = GetCssClass(lnk)
End Sub
The problem is now that the click event is not always fired. On first click, nothing happens, but on second click on a tab, the click event is correctly triggered. Any clue ?
Edit3: Could it be that the value stored in the hidden field is reset each time the masterpage is reloaded (I mean, each link points to a couple masterpage + content page) ?

You need to use <%= ... %> (i.e. replace # with =).
The hash form is used with data binding, you want to just create output.
For .NET 4 prefer <%: ... %> (use a colon) to automatically do HTML encoding.

I have quickly tested a solution that might work for you. I'm just not sure where your 'currentlink' variable comes from. I have implemented it as a hidden field here.
In Masterpage.aspx:
<asp:HiddenField ID="currentLink" runat="server" />
<asp:LinkButton ID="LinkButton1" runat="server">Home</asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server">Page1</asp:LinkButton>
In code behind:
use your original GetCssClass function add this:
Protected Sub LinkButton_PreRender(ByVal sender As Object, ByVal e As System.EventArgs)
Handles LinkButton1.PreRender, LinkButton2.PreRender
Dim lnk As LinkButton = CType(sender, LinkButton)
lnk.CssClass = GetCssClass(lnk)
End Sub
I have put it in PreRender because i was using the LinkButton click events to set the hidden field value (and Click happens after Load but before PreRender):
Protected Sub LinkButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles LinkButton1.Click, LinkButton2.Click
Dim lnk As LinkButton = CType(sender, LinkButton)
currentLink.Value = lnk.ID
End Sub
also, if there are numerous Linkbuttons, you may want to declare like:
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton_Click" OnPreRender="LinkButton_PreRender">Home</asp:LinkButton>
EDIT:
Here is another solution that will work with cross page postbacks. Not much code but you'll need to put some on every page. Anyway:
Masterpage.aspx:
<asp:LinkButton ID="LinkButton1" runat="server" PostBackUrl="Default.aspx">Home</asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" PostBackUrl="Page1.aspx">Page1</asp:LinkButton>
<asp:LinkButton ID="LinkButton3" runat="server" PostBackUrl="Page2.aspx">Page2</asp:LinkButton>
<asp:LinkButton ID="LinkButton4" runat="server" PostBackUrl="Page3.aspx">Page3</asp:LinkButton>
Masterpage.aspx.vb:
Public Sub SetCssClass(ByVal ctrl As String)
CType(FindControl(ctrl), LinkButton).CssClass = "current"
End Sub
All content pages:
*.aspx:
add this directive to create a strongly typed reference to the masterpage
<%# MasterType VirtualPath="~/MasterPage.master" %>
*.aspx.vb:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Master.SetCssClass("LinkButton1") '' << put the name of the relevant link button here
End Sub

Set the CssClass in the code-behind. This will state your intent more clearly than calling DataBind on your linkbuttons if you use databinding syntax. Since you're doing it for multiple controls maybe stick them in a method called ApplyCssClasses.

I'm not sure why <%= %> isn't working but personally I don't like to mix code and markup, I like to keep them completely separate.
I would suggest setting the CSS class in code perhaps on the page load event.
lnkPopulate.CssClass = "current"

<%# ... %> will work if you're OK with doing LinkButton1.DataBind() in your code-behind at the appropriate time.

Related

ASP Repeater not showing data

I'm trying to get an alphabet pager working in GridView. It does work, but only one letter shows up in the repeater that I'm using to show the letters. I've read other posts and looked at my code and it seems like it should be working, but it's not.
Any help would be appreciated.
Here is my html
<asp:Repeater ID="rptAlphabets" runat="server">
<ItemTemplate>
<asp:LinkButton ID="lnkBtn1" runat="server" Text='<%#Eval("Value")%>' Visible='<%# Convert.ToBoolean(Eval("Selected"))%>' OnClick="Alphabet_Click"/>
<asp:Label ID="lblAlpha" runat="server" Text='<%#Eval("Value")%>' Visible='<%# Convert.ToBoolean(Eval("Selected"))%>' />
</ItemTemplate>
</asp:Repeater>
Here is my code behind
Private Sub GenerateAlphabets()
Dim alphabets As New List(Of ListItem)()
Dim alphabet As New ListItem
alphabet.Value = "ALL"
alphabet.Selected = alphabet.Value.Equals(ViewState("CurrentAlphabet"))
alphabets.Add(alphabet)
For i As Integer = 65 To 90
alphabet = New ListItem()
alphabet.Value = [Char].ConvertFromUtf32(i)
alphabet.Selected = alphabet.Value.Equals(ViewState("CurrentAlphabet"))
alphabets.Add(alphabet)
Next
rptAlphabets.DataSource = alphabets
rptAlphabets.DataBind()
End Sub
I'm using most of the code from an aspsnippets method.
EDIT :
I'm calling the GenerateAlphabets from my Page_Load
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
ClearMessages()
If Not IsPostBack Then
ViewState("CurrentAlphabet") = "ALL"
Me.GenerateAlphabets()
BindGrids()
BindDropDownListBoxes()
End If
Catch ex As Exception
Me.HandleError(ex)
End Try
End Sub
Change your LinkButton code like this.
<asp:LinkButton ID="lnkBtn1" runat="server"
Text='<%#Eval("Value")%>'
Visible='<%# Convert.ToBoolean(Eval("Selected")) = False %>'
OnClick="Alphabet_Click"/>
Reason: You are hiding all LinkButtons that are not currently selected. You should be showing them instead.

How to dynamically add controls and preserve Viewstate?

I'm attempting to use Controls.AddAt(), but it apparently breaks controls at later indexes:
Here's my minimal example:
Aspx put in a form:
<asp:DropDownList runat="server" ID="ddl" />
<asp:Button Text="text" runat="server" OnClick="Unnamed2_Click" />
Code Behind:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
ddl.Items.Add("Click the button")
'Controls.Add(New HyperLink) 'Works fine, but is put at end of collection.
'Controls.AddAt(2 ,New HyperLink) 'Is also safe but I wanted the control first
Controls.AddAt(0, New HyperLink) 'ddl loses it's item after postback
End If
End Sub
On the first postback of the page after calling AddAt, the DropDownList loses it's item. It doesn't matter what kind of control I add even HTMLControls. Viewstate is not disabled.
How do I dynamically add controls without breaking others?
If you used a PlaceHolder to add your HyperLink into, it would not mess up the rest of the page:
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<asp:DropDownList ID="ddl" EnableViewState="true" runat="server" />
<asp:Button ID="bn1" Text="text" OnClick="Unnamed2_Click" runat="server" />
With code like
Protected Sub Unnamed2_Click(sender As Object, e As EventArgs) Handles bn1.Click
Dim newItem = "Click the button" & DateTime.Now.ToString("HH:mm:ss")
ddl.Items.Add(newItem)
ddl.SelectedIndex = ddl.Items.Count - 1
PlaceHolder1.Controls.Add(New HyperLink With {.ID = "hyp", .Text = "Hyperlink here"})
End Sub
And always give your asp:Controls an ID if they take one.

passing variable between button and sub vb.net

hello i am trying to pass parameters from asp LinkButton to a sub routine and it doesn't work
this is the linkbutton
<asp:LinkButton runat="server" ID="linkId" OnClick="doSomething(10)">ID
</asp:LinkButton>
and this is my sub
Public Sub doSomething(ByVal mon As Integer)
MsgBox("this is the number : " & mon)
End Sub
can some one tell me how can we make this work in VB.net
Try with CommandArgument property
<asp:LinkButton runat="server" ID="linkId" OnClick="doSomething"
CommandArgument="10">ID</asp:LinkButton>
and
Public Sub doSomething(sender As Object, e As EventArgs)
Dim btn As LinkButton = DirectCast(sender, LinkButton )
Dim msg As String = "this is the number : " & Int32.Parse(btn.CommandArgument)
End Sub
You cannot pass anything directly to an event handler. But you can use LinkButton's CommandArgument property:
<asp:LinkButton runat="server"
ID="linkId"
OnClick="LinkButton_Click"
CommandArgument="10">ID
</asp:LinkButton>
in your codebehind (with the correct signature for this event):
Protected Sub LinkButton_Click(sender As Object, e As EventArgs)
Dim lb = DirectCast(sender, LinkButton)
Dim ID As String = lb.CommandArgument;
End Sub
Note that you should not use a MessageBox in an ASP.NET environment since it would be shown on the server and not in the browser.
You don't have to use the DirectCast method. It may make more sense for your sub to look like this:
Public Sub doSomething(sender As Object, e As CommandEventArgs)
Dim msg As String = "this is the number : " & e.CommandArgument
End Sub
You can also store a second value in the CommandName property of the control and use it the same way.
edit: With a slight change to your control, use OnCommand instead of OnClick:
<asp:LinkButton runat="server" ID="linkId" OnCommand="doSomething"
CommandArgument="10" Text="ID" />

Addhandler, button.click not firing using VB.NET

I am experiencing a problem with buttons and AddHandler. It only works if I use AddHandler Button1.click, AddressOf... in Page_load, but if I create the button dynamically in one of the sub routines, the event doesn't fire.
For example,
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
</asp:DropDownList>
<asp:ScriptManager id="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel id="UpdatePanel1" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="False">
<contenttemplate>
<asp:PlaceHolder id="PlaceHolder1" runat="server"></asp:PlaceHolder>
</contenttemplate>
</asp:UpdatePanel>
<asp:UpdatePanel id="UpdatePanel2" runat="server" UpdateMode="Conditional">
<contenttemplate>
<asp:Label id="Label2" runat="server" Text="Label"></asp:Label>
</contenttemplate>
</asp:UpdatePanel>
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Label1.Text = Date.Now
ScriptManager1.RegisterAsyncPostBackControl(DropDownList1)
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
Label2.Text = "Panel refreshed at " + Date.Now.ToString()
End Sub
Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged
Dim b As New Button
b.Text = "Click"
ScriptManager1.RegisterAsyncPostBackControl(b)
AddHandler b.Click, AddressOf Button1_Click
PlaceHolder1.Controls.Add(b)
UpdatePanel1.Update()
End Sub
The dropdownlist works, but the button doesn't. What am I doing wrong?
You have to regenerate your dynamically created controls on every postback (at last in Page_Load, better in Page_Init). You have to set the ID of the controls accordingly because ASP.Net needs it to identify which control caused a Postback and to handle the appropriate events.
You could save the number of created buttons in ViewState and use this to regenerate them on Page_Load. Increase the number when you add a new button. Use this number also to make the Button's ID unique(append it to the ID) to ensure that its the same on every postback.
For further informations, have a look the Page-Lifecycle and ViewState with dynamically added controls.
Edit: As Joel commented, if you only need one Button you can set it's ID statically, but you have to regenerate it on postback f.e. to handle its click-event.
Just to aid anyone who has this problem and isn't quite sure how to implement. Here's a quick example.
This example starts out by displaying a dropdownlist. When user selects something from the dropdown, another dropdownlist appears.
I typed this off the top of my head, so it MAY contain errors, but you get the idea =)
In the aspx file, add a placeholder:
And in your codebehind:
...
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
'Store control count in viewstate
If Not IsPostBack Then ViewState("ControlCounter") = 1
'Rebuild dynamic controls on every postback so when page's life cycle hits Page_Load,
'selected values in the viewstate (asp.net default behavior) can be loaded into the dropdowns
Build_Dynamic_Controls()
End Sub
Protected Sub Build_Dynamic_Controls()
'Clear placeholder
myPlaceholder.Controls.Clear()
'This is where the control counter stored in the viewstate comes into play
For i as Integer = 0 To CInt(ViewState("ControlCounter") -1
Dim ddlDynamic as New DropDownList With {
.ID = "ddlDynamicDropdown" & i,
.AutoPostBack = True
}
'This is the event that will be executed when the user changes a value on the form
'and the postback occurs
AddHandler ddlDynamic.SelectedIndexChanged, AddressOf ddlDynamic_SelectedIndexChanged
'Add control to the placeholder
myPlaceholder.Controls.Add(ddl)
'Put some values into the dropdown
ddlDynamic.Items.Add("Value1")
ddlDynamic.Items.Add("Value2")
ddlDynamic.Items.Add("Value3")
Next i
End Sub
Protected Sub ddlDynamic_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
'When a dropdown value is changed, a postback is triggered (autopostback=true)
'The event is captured here and we add another dropdown.
'First we up the control count:
ViewState("ControlCounter") = CInt(ViewState("ControlCounter")) + 1
'Now that the "total controls counter" is upped by one,
'Let's recreate the controls in the placeholder to include the new dropdown
Build_Dynamic_Controls()
End Sub
...

Why is my CommandArgument Empty?

I have an ASP.Net page, which displays a list of options to the user. When they select from the list, it does a post back and queries a sql server. The results are displayed in a listview below the options in an update panel. Below is a snippet of the ItemTemplate:
<asp:LinkButton Text="Save IT" OnCommand="SaveIt" CommandArgument="<%# Container.DataItemIndex %>" runat="server" />
The DataItemIndex does not appear, so my commandargument is empty. However, the object sender is the button, which shows the item.
Why is the index item not appearing in the CommandArgument?
Could it be the post back? If so, why would it be the post back? Is there a way around it?
Edit:
Sorry, from my attempts to solve it before, I posted bad code, but it still isn't appearing.
Resolution:
I found another work around in that the sender of the OnCommand is the link button, which has the CommandArgument. I will chalk this issue up to be an issue with multiple postbacks and javascript.
You can't use the <%= %> syntax inside properties on a tag with a runat="server" attribute. I'm surprised the code will even run. :)
UPDATE:
You probably want to use the ItemDataBound event on the repeater, find the linkbutton and set the CommandArgument property.
Not very elegant, but here's a VB.NET sample.
Private Sub Repeater1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles Repeater1.ItemDataBound
Select Case e.Item.ItemType
Case ListItemType.Item, ListItemType.AlternatingItem
Dim b As LinkButton = e.Item.FindControl("btn")
b.CommandArgument = e.Item.ItemIndex
b.DataBind()
End Select
End Sub
You're not setting it
You possibly want
<%# Container.DataItemIndex %>
or
<%= Container.DataItemIndex %>
:)
Try
<asp:LinkButton Text="Save IT" OnCommand="SaveIt" CommandArgument="<%# Container.DataItemIndex %>" runat="server" />
You were missing the "#" sign.
This site really helped me with this problem: http://forums.asp.net/t/1671316.aspx
The issue I ran into was that I was being passed null arguments in the commandargument when I clicked on the button a second time. As the post above explains, this is because commandargument is only set in the databind event. So, to fix this, include a databind event in the page_load sub
Ex. (VB)
Private Sub BindSelectButtons()
'Purpose: bind the data to the select buttons for commandargument to be used
Dim i As Integer
For i = 0 To gridview1.Rows.Count - 1
gridview1.Rows(i).Cells(8).FindControl("btnID").DataBind()
Next
End Sub
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
'Rebind select buttons so that the commandargument refreshes
BindSelectButtons()
End Sub
Make sure View State is enabled
e.Row.EnableViewState = true;

Resources