ASP.NET drop down selected index not changed event - asp.net

There is an event onSelectedIndexChange for DropDownList in ASP.NET which triggers when a selected index is changed for a dropdown.
I have encountered a situation where I need to trigger similar kind of event when SelectedIndex of DropDown does not change upon selection.
I am totally puzzled what to do in such a case?
Any help/references will highly be appreciated.
Thank you.

I think that is normal. The event is SelectedIndexChanged and you said you selected the same item that was previously selected before. So the index remains the same, not changed, and the event won't fire. May be you look at OnClick.
The issue is that you have not changed the index when you clicked the second time, so the dropdown is still waiting for you to change it

Assuming you have another server-side control on your page that causes a postback, you could write a routine in the postback event for the other control that compares the current selection with the previous selection and fire a custom-event (or the routines you want to happen) if the value has not changed.
That said, I have to imagine there's an easier way to accomplish the overall goal you're trying to achieve, but you'll have to be a little more specific in your question.
UPDATE
I have to assume that you are using the value from the dropdown when you are processing the form. Why not start off with the dropdown hidden and the linkbutton shown? Just select a default from the dropdown list and allow the user to change it as needed.
Here's a fiddle showing that behavior: http://jsfiddle.net/rjaum/

That's fairly easy.
You can achieve this using javascript/jquery/server side code etc. Assuming user does click the control.
Something like this on pageLoad
PageLoad()
{
YourDropDownList.Attributes.Add("onclick","javascript:CallHelloWorld();return false;");
}
Then on server side you can decorate a method with WebMethod attribute
[WebMethod()]
public static string HelloWorld()
{
return "Hello foo";
}
On your client side aspx you can use jQuery to call your webmethod
<script language="text/javascript">
function CallHelloWorld()
{
// Call HelloWorld webmethod using jQuery $.ajax
}
</script>
Edit
You can use a radiobutton list instead of dropdownlist. That way, on client side you can check the event when the radio button is clicked that it is checked or not (if its checked fire your event).
Edit
Also try looking at this thread if you want to use dropdown list specificallyFire event each time dropdown list is selected with JQuery

assign an a event handler to the selected index changed event and set autopostback to true
in markup
or code behind
mydropdownlist.SelctedIndexChanged += NameOfMethod
the handler is then defined like this
protected void NameOfMethod(object sender, EventArgs e)
{
//your code here
}
update
by definition the selectedindexchanged event would only fire when the index changes. if you want to force the postback that will require some javascript. here is an example of how to do that with jquery
$(function() {
$('select').change();
});

Related

Add buttons with css & eventhandlers in Page_Load

Im trying to add buttons to a placeholder, each with an eventhandler to the same method.
if (!this.IsPostBack)
{
foreach (Entry ent in results)
{
HtmlButton btn = new HtmlButton();
btn.ServerClick += new EventHandler(resultSelected);
btn.InnerText = ent.name;
btn.ID = ent.ID.ToString();
PlaceHolder1.Controls.Add(btn);
}
}
1)
The button is added to the page but when its clicked the method (resultSelected) is not called, only Page_Load again. And when it enters Page_Load the PlaceHolder is empty (the button is not displayed on the page). How do I accomplish what Ive tried to do?
2) How do I assign CSS classes to buttons created in this way?
It's quite common issue when you start working with ASP.NET for the first time - adding dynamic controls on server side.
First thing is that You have to add those controls and assign eventhandler on every page request - on every postback as well. For proper event handling and restoring ViewState, you have to assign to them the same IDs and apply the same hierarchy.
Controls needs to be added before Page Load event - most convinient would be adding them on in overriden CreateChildControls() method, which is fired on Postback before OnLoad method.
Events are fired after OnLoaded method, so if you will create any control in for example OnPreRender/Render method - any event won't be fired.
This is most straightforward approach with some details skipped in my description. For more detailed information please read about ASP.NET Application Life Cycle.
As for the second part of your question, you can either use explicit styles setting with Style Property or it should be also possible to add class attribute using Attributes Property, but right now i'm guessing, cause i think HtmlButton doesn't have CssClass property.

TextBox keydown event at server side in asp.net

i have a textbox on a page, now whenever any age number is entered in that page, that page should be loaded in my datalist, i have created rest of the thing, but i am not getting how to trigger the textbox onkeydown event from asp.net, i know working with that from javascript, but the problem is i have below things done in that function:
it applies the currentpage value to the static variable from textbox
it binds the datalist
it enable disable the next previous buttons accordingly
and i dont think this i can do from javascript, anyone have any resolution, how this could be achieved from server side, onkeydown event
You can capture the keydown event in a javascript function then do a AJAX call to the server. If this does not suit you, then you could try manually do postback in javascript.
So in your textbox:
mytextBox.Attributes.Add("onkeydown", "return doDataListBind()");
Now in the javascript function:
function doDataListBind()
{
__doPostBack("myTextBox"); // etc, etc
// some other code here...
}
More info can be found here:
http://geekswithblogs.net/mnf/archive/2005/11/04/59081.aspx
http://www.asp.net/ajaxlibrary/AjaxControlToolkitSampleSite/
Try looking into or using either:
AJAX Control Toolkit, or
JQuery Autocomplete Plugin
Alternatively you could try to call _postback() function from a client side event/function for your textbox in javascript

Conditionally trigger a full page postback from a link button inside an update panel

How do I conditionally trigger a full page postback from a link button inside of an update panel?
I have a custom control that contains its own updatepanel with a link button nested inside of it. When the link button is pressed I want its event handler to have the option of either letting the control update as normal or doing a full postback on the page.
Here is the control hierarchy:
Page
Custom Control
UpdatePanel
LinkButton
Event handler Pseudo code:
LinkButton Click Handler Begin
If is a partial post back AND a full postback is needed
Page.DoFullPostback
End If
End Handler
Note: I aways need the partial postback to happen. I was considering injecting a __DoPostback in the controls markup but this seems hacky to me.
Thanks for your help!
Sorry, I'm not familiar with the VB, so my example source will be written in C#:
protected void btnLink_Click(object sender, EventArgs e)
{
bool isAsync = ScriptManager.GetCurrent(Page).IsInAsyncPostBack;
bool postBackIsNeeded = true;
if (isAsync && postBackIsNeeded)
{
ScriptManager.GetCurrent(Page).RegisterPostBackControl(btnClick);
string postback = Page.ClientScript.GetPostBackEventReference(
btnClick,
string.Empty
);
ScriptManager.RegisterStartupScript(
btnClick,
btnClick.GetType(),
"postback",
postback,
true
);
}
}
The main idea is to change the type of postback of your LinkButton control. If neccessary it should be changed to full postback instead of partial during the async postback event. Right after this, another postback script should be generated and it should be executed as soon as the page will be returned to client.
And the last thing - use loop detection condition (if (isAsync && postBackIsNeeded) in my case) otherwise postback will be infinite.
The easiest approach is to create a hidden button somewhere on your page, outside of any UpdatePanels. When you need to do a full postback, use JavaScript to either click the button or issue __doPostback() to it. You can achieve a partial postpack programmatically in JavaScript by calling __doPostback() on an UpdatePanel itself, or to a button inside one.

UserControl events not working for first time

I am calling my user control in a web page dynamically.
For the first time when I click the button on user control, the event is not firing. When I click the same for a second time, the events are firing..
Can anyone help me?
Sounds like the hookup to the button OnClick event is not occurring on every page load, which is required.
Can you guarantee that the hookup is being performed when you add the control and after a poastback to the page? I always put my event hooks in the Page_Init or Page_Load event handlers and outside of any Postback check. Try putting a breakpoint on the Handler hook up and see if the breakpoint gets "hit" twice.
An event hookup for a button would look similar to:
protected void Page_Load(object sender, EventArgs e)
{
btnSearch.Click += new EventHandler(btnSearch_Click); // breakpoint on this line
}
The client id of the control is derived from the ID of all containing controls that are marked with the INamingContainer interface. So, make sure that ALL controls in the hierarchy have a fixed ID.
For example if you have a Button control inside a Repeater, the ID of the button and the repeater are concatenated to make the client ID for the button. So both the repeater and the button should have the same ID across postbacks.
You can compare the HTML for the first request with the HTML of the second request to quickly determine if this is the problem.
Assign an ID for your dynamically created control -- otherwise no events will be fired.
Are you waiting for the download of full page before pressing the button?
The events are javascript functions hidden by ASP.Net in the page, that maybe not present at the time of your clicking.

Determine which button inside a user control sent the event

I have a user control that has several buttons.
On page_load, I want to run a method unless a specific button was pressed.
When I check the sender on page_load inside the user control, I just get the name of the user control and not the button itself.
Is there a way that I can determine what button was pressed on page_load? Otherwise I will have to come up with some hacky method to solve the issue.
I think you can check Request.Form ("__EVENTTARGET") - that should contain the ClientID of your control.
This refers to the value of a hidden field the ASP.NET event handling framework uses to keep track of what the user clicked. When the user triggers a post-back, some JavaScript on the page sets this hidden field to the ClientID of the control you clicked before submitting the form.
Can you create a property in your user control to return the clicked button (or set a flag or whatever), an set it in each button's click event inside the user control?
Are you sure you're handling the page model correctly? The Page Load event happens (to build the server side object model), then your control is going to handle the button click event bound to the control.
Page Load can come for any number of postback reasons besides buttons in your user control being clicked.
What about buttons in other controls on the page?
There's sometimes good reasons to do this, but I also I worry that you're just hacking around the ASP.NET page model.
Here's a simple way to check if a specific button was pressed:
protected bool isButtonClicked(string buttonName)
{
bool isClicked = false;
foreach (string ctl in this.Request.Form)
{
if (ctl.EndsWith(buttonName))
{
isButtonClicked = true;
break;
}
}
return isClicked;
}

Resources