DropDownList events don't fire - c#

I’m having trouble with my DropDownList. The events don’t fire! I've tested it on a separate project, with a DropDownList and a literal. Every time the selected value would change, I would add a little star “*” to the literal. No problems what so ever. But every time I try it on my webpage in the project, it fails.
Here is an image.
protected void ddlConsole_SelectedIndexChanged(object sender, EventArgs e)
{
ltlTesting.Text += "*";
}
UPDATE:
I've tried some things but still with no succes. I hope someone can tell me what i'm doing wrong. I'm wiring the events in the code behind now, but i've added a linkbutton next to the dropdownlist to see if it works.
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
ddlConsole.SelectedIndexChanged += new EventHandler(ddlConsole_SelectedIndexChanged);
lnkGet.Click += new EventHandler(ddlConsole_SelectedIndexChanged);
}
Here is an image to see what's going on. The stripe in the literal at the beginning is added in pageload with the same code the star is added. Just to be sure it doesn't load twice. The "GET" linkbutton works fine. The dropdownlist doesn't...

Have you Set
AutoPostBack="true"
in control properties??
EDIT:
Remove
OnSelectedIndexChanged="ddlConsole_SelectedIndexChanged"
from the markup in the ASPX page and try again only with AutoPostback true and the
event defined in codebehind. The aspx page should look like this:
<asp:DropDownList runat="server" ID="ddlConsole" AutoPostBack="True"></asp:DropDownList>

Is the AutoPostBack of the dropdownlist true ?

Check AutopostBack property of Dropdownlist set it to true :

If picture is right and the AutoPostBack="True", is there any code that sets the value of ltlTesting when page loads?

Add the AutoPostback="True" and OnSelectedIndexChanged="ddlConsole_SelectedIndexChanged" to the ddlConsole attributes. You can delete the OnInit method, since you bound the SeletedIndexChanged event at design time.

Related

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"]

using PreviousPage functionalities without AutoEventWireup

G'day,
I'm using PreviousPage to get values from controls from another page like this:
sPORyear1 = PreviousPage.year1.SelectedItem.Text.ToString();
It works just fine, however I noticed that the events from C# Code Behind (ex. Button click) are not handled properly. I tried making a breakpoint inside the event and it doesn't stop.
After looking at my aspx I noticed this:
AutoEventWireup="true"
When I set that to false, the buttons work properly, but the PreviousPage functionality doesn't work anymore.
The button code:
<asp:Button ID="export" runat="server" onserverclick="export_Click" Text="Export" />
Thanks!
When the AutoEventWireup is set to "False" Change the Page load Handler signature as below for the another page in which you are trying to access the value of previous page
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
}
Please note that the access modifier should be protected not Private in case of Autoeventwireup = "False" Otherwise you will not be able to capture the OnLoad event
this fixed it
Button On Click event not firing

Nested ASP.NET DropDownList SelectedIndexChanged Not Firing

Have run this by my entire dev group to no avail. Seems simple enough, here's the question.
I have a UserControl with a single, non-databound dropdownlist. The UserControl is then dropped onto the masterpage and then also loaded into an inheriting webform that has the control manually loaded onto the page.
No AJAX, straight post-back.
The issue I am running into is that the SelectedIndexChanged event is not firing for the second instance of the DropDownList. The first one fires just fine.
TIA
Here is the code for the ascx:
<asp:dropdownlist id="SelectLanguage" autopostback="true" runat="server" enableviewstate="true">
<asp:listitem>- Select Language -</asp:listitem>
<asp:listitem value="xxx">Netherlands</asp:listitem>
<asp:listitem value="xxx">United Kingdom</asp:listitem>
<asp:listitem value="xxx">United States</asp:listitem>
</asp:dropdownlist>
Here is the CB for the user control:
protected override void OnInit(EventArgs e)
{
SelectLanguage.SelectedIndexChanged += new EventHandler(SelectLanguage_SelectedIndexChanged);
base.OnInit(e);
}
protected void SelectLanguage_SelectedIndexChanged(object sender, EventArgs e)
{
// do something
}
Does the postback actually happen for the second dropdown, or does the page do nothing?
If the postback isn't happening, you have javascript errors on your page.
Not sure exactly how this is, but the FancyBox lightbox jQuery library we're using to do the lightbox effect around the 2nd drop down is somehow messing with the bindings on the back end. No real time to figure out why, just let it be known it does in case anyone else runs into this issue.

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.

Selected Item not being updated?

I've got the following DropDownList control:
<asp:DropDownList ID="SubjectFilter" runat="server" AutoPostBack="True" onselectedindexchanged="SubjectFilter_SelectedIndexChanged"></asp:DropDownList>
SubjectFilter data:
BookStore b = new BookStore();
b.LoadFromXML(Server.MapPath("list.xml"));
SubjectFilter.DataSource = b.BooksList.Select(x => x.Subject).Distinct().ToArray();
SubjectFilter.DataBind();
SubjectFilter.Items.Insert(0, new ListItem("הכל", "Default"));
Everything loads just fine. However in the SubjectFilter_SelectedIndexChanged method, SubjectFilter.SelectedValue is always Default, even though I'm selecting different options.
What is the problem?
Thank you very much.
I'm guessing the above code is from the PageLoad event. You may want to wrap that in a if(!isPostBack) block.
Make sure that in your Page_Load that you only populate the dropdown when IsPostBack is false.
For example
public void Page_Load(...)
{
if (!IsPostback())
UpdateDisplay();
}
When are you binding the drop down? You may any to wrap in an
If(page.ispostback ==false)
It looks like you may be binding on page load, before you check its value..
ViewState is assigned between the Init and Load for an ASP.NET page. Your event handlers occur after load. If you are programmatically setting content in the controls that your user will be using, you want to handle that before ViewState is applied. In other words, move it to Page_Init. Afterwards, ViewState kicks in and you'll see what the user actually selected when your handler executes.

Categories

Resources