BulletedList onClick not firing - c#

Ugh, this is driving me mad
Im trying to build up a dynamic menu from a bulletedList, most menu items are plain links however the log out button needs to perform some cleanup code.
I cant for the life of me get the BullettedLists onclick event to fire.
The BulletedList is inside a user control (if that makes a difference)
Any ideas?
Or - any ideas for an alternative, better solution?
Code below
BulletedList
<asp:BulletedList OnClick="menu_Click" runat="server" CssClass="MainMenu" ID="loggedInMenu" DisplayMode="HyperLink" />
Adding an element
loggedInMenu.Items.Add(new ListItem("Logout", ""));
Click handler
protected void menu_Click(object sender, BulletedListEventArgs e)
{
user.logout();
Response.Redirect("Default.aspx");
}

You're using the wrong DisplayMode for your BulletedList control. You should use a DisplayMode of LinkButton. When you use DisplayMode.HyperLink:
Users can click links to move to
another page. You must provide a
target URL as the Value property of
individual items.
This is from the MSDN docs for this control. (It's about 3/4 of the way down the page.)
When you use a BulletedList control in HyperLink mode, the value of your ListItem is the URL that you're navigating to. So your static page HTML controls would use ListItem.Value as the href attribute of the <a> tag.
Here's what the HTML markup looks like when you use a DisplayMode of HyperLink (it's a plain old HTML anchor tag w/ a href):
<li>One</li>
But since you want to postback, you should set the DisplayMode of your BulletedList control to LinkButton. When you do that, you'll enable a postback back to your page and your event handler will trap the event. You can then process the click appropriately then. The event argument that's passed in (of type BulletedListEventArgs) will have an Index property, and that will tell you what item in your list was clicked.
Here's the updated .aspx code that I used:
<asp:BulletedList ID="bullet" runat="server" DisplayMode="LinkButton"
onclick="bullet_Click">
<asp:ListItem Text="One" Value="1">One</asp:ListItem>
</asp:BulletedList>
Everything else is the same except the DisplayMode, which is set to LinkButton. When I use that, then my bullet_Click event handler is fired when I click a list item.
I hope this helps!!

Related

How to get Button Id inside "data-content" atrribute of html tag in code-behind file to fire evnt

In vb .aspx Inside data-content attribute i have my TextBox and Button Control . But there id not visible in code-behind .i need to fire evnt on button. how to fire event on button??
<a
data-content='<asp:TextBox runat="server"></asp:TextBox><asp:Button ID="btnEdit" runat="server" Text="Edit" />'
data-html='true' data-toggle='popover' href='#' title='UserName'><%#Eval("Name")%></a>
I need to fire event in code-behind... Any Suggestion
If memory serves me correctly, the ID of an asp control, like asp:Button is essentially the name of the control variable in code-behind. You need to reach it from something like the aspx.vb file
The attribute of OnClick="Event_Name" could be helpful in this example.
If you need a client-side click, then you might want to work with the ClientID data member or the onclick html attribute of the generated tag.

List all asp.net controls that have a matching onclick attribute after one is clicked

I have a bunch of LinkButtons on an asp.net page and need to set the visibility property of all the other LinkButtons on the page that have the same onclick attribute. I'm looking for a server side solution.
In the click handler I've gotten as far as listing the LinkButtons on the Page recursively but am stumped at how to tell if each LinkButton I find does or doesn't have a matching click handler.
The EventHandler property doesn't seem to contain any good info...
What is the best way to approach this?
You can give your linkbuttons a custom atttribute (for simplicity it can be the same as event handler name) e.g.
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton_Click" tag="LinkButton_Click">LinkButton1</asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" OnClick="LinkButton_Click" tag="LinkButton_Click">LinkButton2</asp:LinkButton>
Then in your server-side code you can simple compare the attributes
protected void LinkButton_Click(object sender, EventArgs e)
{
// your recursive code retrieving current linkbutton
// ...
if ((sender as LinkButton).Attributes["tag"] == currentLinkbutton.Attributes["tag"])
{
// do your magic
}
}
An ugly solution would be to give all of those buttons the same CommandName attribute. Then you can just search for all link buttons with that attribute. Otherwise I am not sure that there is a great way to track the event handler used by each LinkButton.
Did you try linkbtn.Attributes["OnClick"]

Link Button : "right click and open in new tab" not working

I am trying to right click on a LinkButton and open it in a new tab or seperate window page displays nothing. I found some solution for the use of Hyperlink button as it has property to set target to "_blank" but LinkButton has not any target attribue.
I want to use LinkButton instead of hyperlink button, its just because i can't set command arguement or command name on hyperlink button and can't fire an event on it.
<asp:LinkButton ID="lnkHeadingHindi" Text='<%#Patrika.Common.ConvertNews(Eval("strMainHeadingHin").ToString())%>' CommandArgument='<%#Eval("intNewsId") %>' runat="server"></asp:LinkButton>
It would be great if anybody has a solution and let me know in case of any concern.
Thanks !!
Based on the accepted answer to this question, if you want to perform a POST (such as a LinkButton does) but have the result open in a new window, you need to add target="_blank" to the form on the page, not the link itself.
Obviously you don't want to do this when you initially render the page, as everything that caused a postback would open in a new window.
Instead, try adding the following attribute to your LinkButton:
OnClientClick="$('form').attr('target', 'blank')"
This will dynamically set the form attribute just before the form is posted back by a click to the link.
Note that this doesn't give the right-click functionality you want, but it does work to open in a new window on a left-click.
If you don't have access to JQuery, you'll need to do something like
protected void Page_PreRender(object se, EventArgs e)
{
this.Page.Form.ID = "someUniqueID"; // unless your form already has an ID
yourLinkButton.OnClientClick =
"document.getElementById('" +
this.Page.Form.ClientID +
"').setAttribute('target', '_blank')";
}
From the docs
Use the LinkButton control to create a hyperlink-style button on the Web page. The LinkButton control has the same appearance as a HyperLink control, but has the same functionality as a Button control. If you want to link to another Web page when the control is clicked, consider using the HyperLink control.
As this isn't actually performing a link in the standard sense, there's no Target property on the control (the HyperLink control does have a Target) - it's attempting to perform a PostBack to the server from a text link.
Depending on what you are trying to do you could either:
1) Use a HyperLink control, and set the Target property
2) Provide a method to the OnClientClick property
that opens a new window to the correct place.
3) In your code that handles the PostBack add some JavaScript to fire on PageLoad that will open a new window correct place.
If you like when click the link button,then open new window,
please see this
insert base tag like this
<head>
<base target="_blank" />
</head>
If you want to pass some information to the page using hyperlink, pass it in the url using QueryString.
<asp:HyperLink id="hyperlink1"
NavigateUrl="~/MyPage.aspx?intNewsId=10"
Text="ClickMe"
Target="_blank"
runat="server"/>
You can't have it both ways, you'll have to choose between:
1) the linkbutton executing some code in the current page
2) a hyperlink opening another page in a new window
I guess you want to have the linkbutton executing some code in the new page, but that's impossible.
or if u like use . anger tag
Just render an anchor with href set to appropriate url and set the target attribute to _blank it will open the url into new window
<a href="urlOfThePage" target="_blank" >Click me</a>

Dynamically adding a command button to a GridView

I'm having an issue with trying to add a button to my grid. My GridView is first loaded with data in the PageLoad event.
I'm then taking the data in the first cell of each row, and creating a button that will link to a URL. To get the URL, I have to run a query with the data in the first cell as a parameter. I was doing this in the RowDataBound event at first, but hitting that query for every row was making it really slow.
So I decided to add a button that would retrieve the URL only when you clicked the button.
Here's my GridView:
<asp:GridView ID="gvResults" runat="server"
OnRowDataBound="gvResults_RowDataBound"
OnRowCommand="gvResults_RowCommand">
</asp:GridView>
And my code:
protected void gvResults_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItem != null)
{
LinkButton lb = new LinkButton();
lb.CommandArgument = e.Row.Cells[0].Text;
lb.CommandName = "NumClick";
lb.Text = e.Row.Cells[0].Text;
e.Row.Cells[0].Controls.Add((Control)lb);
}
}
protected void gvResults_RowCommand(object sender, CommandEventArgs e)
{
switch (e.CommandName.ToLower())
{
case "numclick":
string url = GetUrl(e.CommandArgument.ToString());
Response.Redirect(url);
break;
default:
break;
}
}
The grid generates fine, the button gets added to the grid for each row. But when I click on it, the RowCommand event doesn't fire, and the page just refreshes.
Does anyone know what the issue is?
Why use a dynamic button at all? You can easily put the linkbutton directly into the markup of the gridview (as long as you don't mind using a template field) and there will be no need to mess around with the RowDataBound event.
Your markup would look something like the following:
<Columns>
<asp:TemplateField HeaderText="SomeHeaderText">
<ItemTemplate>
<asp:LinkButton ID="lnkBtn" runat="server" CommandName="NumClick" CommandArgument= '<%# (string)Eval("dbValue") %>' Text='<%# (string)Eval("dbValue") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField></asp:BoundField>
<asp:BoundField></asp:BoundField>
<asp:BoundField></asp:BoundField>
</Columns>
Add breakpoints to the RowCommand event and make sure that you can hit the breakpoints.
The problem may lie elsewhere.
Also, make sure that you're not databinding on postback.
You have a big trouble with your code. It's pretty hard for me to explain what's your big mistake, but I can easily tell you how to fix.
The problem is that you generate a new button inside the RowDataBound event, definitely the wrongest choice. The button gets rendered because it exists after that event when page renders, but doesn't exist before data binding. If you bind data everytime you load the page (even during postback) the button still gets rendered because you generate a new button.
But since the button doesn't exist before data binding, it cannot raise events. You must declare the button from markup into a template of GridView, then access it not by using new LinkButton() but by using e.Row.Cells[0].FindControl("buttonId") and set its text. Then, you have to set its markup in order to fire its own Command event (not RowCommand) and handle it as you used (don't forget to set CommandArgument during data binding)
[Edit] I also made a mistake: controls inside data bound controls also don't exist before data binding. But they are initialized not with new Control() (by the private methods of data bound control) but with Page.LoadControl(typeof(Control)). That's the first thing you must fix when you load controls dynamically!!
Because the control is added dynamically on databind and you have to databind the gridview for each postback, the control being "clicked" is different each time. The event doesn't fire because at the time it needs to fire it doesn't exist as it did in the last iteration of the page.
I notice you don't have any logic determine if the button should be there, and it always goes into cell[0].
You should place this button into a TemplateItem so that it exists properly. If you have a need to do it in code-behind, you are probably better served doing it in the RowCreated event.

FindControl doesn't work with bind server tag, why?

I have a FindControl in OnLoad event to find my button on page i.e.:
protected override void OnLoad(EventArgs e)
{
DataBind();
control button = Page.FindControl("myButton");
}
on my aspx page I have
<asp:Button runat="server" ID="myButton" />
If I only have this, everything works, when I pass in the OnLoad, button is not null and I can execute what I want. The problem is when I add dynamic text in my aspx:
<asp:Button runat="server" ID="myButton" Text='<%# "Here is my dynamic text pulled from a XML" %>' />
Then the FindControl finds nothing and the button is null.
Adding a binding server tag on aspx isn't suppose to delay anything right? When I inspect the Page object I have some controls in Controls collection, but I'm unable to find myButton.
Any idea on what I am doing wrong?
EDIT
People seem to think that my code example is my real code but it isn't, So I use FindControl because I need to since I have nested controls and I cannot access it directly and I use binding because the dynamic text I'm putting is inside a ContentTemplate which I can override in other page aspx.
The question I asked was more specific to the fact that I have traced the problem where my FindControl returns null because a newly implement behaviour which is the binding.
Improving the code example isn't a solution or an explanation to the fact that if I put a <%# %> tag in my aspx page, the FindControl in the OnLoad event return null.
EDIT 2
the bind tag alone seems to not be the culprit but the DataBind() to populate them. Whether or not I have bind tag, putting DataBind() before the FindControl makes the myButton to be null. Correction in code example was made.
In here MSDN says that :
PreRender : Each data bound control whose
DataSourceID property is set calls its
DataBind method.
It looks like you're not using DataSourceID of your data bound control, but moving your FindControl code to PreRender event might help.
The Page.FindControl() method will only search the imediate collection of controls that are associated with Page. It will not recurse down the entire control tree, so if your button is contained within another control it will not be found. You would need to call the FindControl method on the containing control.
If you want to access a button on your page, you can directly refer to the button as -
this.myButton
And as far as assigning values is concerned, you can do it like this in your server code -
this.myButton.Text = "Dynamic Text";
<%# xyz %> is only used when you are databinding the controls, for e.g. in a DataGrid, GridView, etc.
In your override dont you want to call base.OnLoad(e) in your method first ?

Categories

Resources