Adding "onclick" attribute to asp.net dropdownlist item - asp.net

I can add an attribute to items in a RadioButtonList item like so:
PaymentMethodDropDownList.Items[0].Attributes.Add("onclick", "javascript:showNoMethods();");
PaymentMethodDropDownList.Items[1].Attributes.Add("onclick", "javascript:showCreditCardMethod();");
PaymentMethodDropDownList.Items[2].Attributes.Add("onclick", "javascript:showSendPaymentMethod();");
However, when I try to add the attributes to a DropDownList control it doesn't seem to work. I would expect it to be similar.

This cannot be done in the same way as a radioButtonList, for a dropdownlist, the correct attribute event name is "onchange" instead of "onclick".
The event should be attached to DropDownList Itself and not the items as follows:
PaymentMethodDropDownList.Attributes.Add("onchange",
"showCreditCardMethod();");
Also, this is a little bit more complicated and requires a custom javascript function to perform a different action depending on the option selected. Here's an example:
PaymentMethodDropDownList.Attributes.Add("onchange",
"handleDropDownEvents(this);");
Custom Javascript function: this assumes that values for the dropdown items are "CreditCard" and "SendPayment".
<script type="text/javascript">
function handleDropDownEvents(e){
if(e.value == "CreditCard"){
showCreditCardMethod();
}
else if(e.value == "SendPayment"){
showSendPaymentMethod();
}
}
</script>

Actualy for a DropDownList in ASP .Net, the property you're looking for is OnSelectedIndexChanged or OnTextChanged . Both does quite the same job.
Hope this help ;)

Related

How to change the visibility of CascadingDropDown control

What is the preferred method to change the visibility property of a .NET Ajax Control Toolkit CascadingDropDown control? I would like to render the control "invisible" when a null value is returned from a query.
It appears that "OnSelectedIndexChanged" event does not fire from the <asp:DropDownList> when using the toolkit extender.
Honestly, I would just target the DropDownList that the CascadingDropDownExtender is attached to with the display:none css style. You could do this in javascript on the page like this:
<script type="text/javascript">
function hideDDL(){
// Get the DropDownList by its ID value
var ddl = document.getElementById("<%= myDropDownList.ClientID %>");
// If there are no items in the drop down, hide it
if (ddl.options.length == 0)
ddl.style.display = "none";
}
</script>
And then, in your DropDownList markup, just add the function above to the client-side onchange event:
<asp:DropDownList runat="server" ID="myDropDownList" onchange="hideDDL();" ... >
...
</asp:DropDownList>
Note: Obviously, you will want logic in the javascript function to indicate whether or not the DropDownList should be hidden (such as checking to see if the control has no elements to select, etc). If you have trouble with that, let me know and I can try and help with that too.
EDIT: I have added a possible example of said logic =)

How to specify ControlID attribute of Ajax Update Panel for dynamically created controls

If a control such as checkboxlist is created dynamically.
like this
CheckBoxList CbxList = new CheckBoxList();
CbxList.ID = "Cbx";
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
CbxList.Items.Add(new ListItem(ds.Tables[0].Rows[i]["Name"]
.ToString(), ds.Tables[0].Rows[i]["ID"].ToString()));
}
ph.Controls.Add(CbxList);
If on the selectedIndexChange event of the created checkboxlist(cbx) if i am updating an ajax update panel how should i specify the ControlID Attribute. I did try Cbx in my case but it says no controls and off course that control is not created yet. So how to handle this issue
The only thing that I can think of needing a control ID is the triggers collection; if that is the case, why not put the checkboxlist within the updatepanel, and use an updatemode="always" on the panel itself?
If I understand your question, you want each checkbox to have an ID?
In that case, don't use a CheckBoxList, but use place holder instead, and add CheckBox controls to it.
However, I think the way you do it, they should get IDs such as 'Cbx_0','Cbx_1',...

general method to clearform in asp.net?

I am using master page with content pages. I want to write a genral method to clear textboxes and for dropdownlist set index to 0. Please guide on this.
A Server-Side Approach
If you want to clear the TextBoxes and DropDownLists on postback, you could recurse through the page's Controls collection and for each control see if it's a TextBox or DropDownList. Here's such a function in C#:
void ClearInputs(ControlCollection ctrls)
{
foreach (Control ctrl in ctrls)
{
if (ctrl is TextBox)
((TextBox)ctrl).Text = string.Empty;
else if (ctrl is DropDownList)
((DropDownList)ctrl).ClearSelection();
ClearInputs(ctrl.Controls);
}
}
To use this you'd call ClearInputs passing in the control collection you want to search. To clear out all TextBoxes and DropDownLists on the page you'd use:
ClearInputs(Page.Controls);
A Client-Side Approach
An alternative tactic would be to use a client-side approach. Namely, use JavaScript to recurse through the DOM and clear/reset the textboxes and drop-downs on this page. The following JavaScript uses the jQuery library to simplify things:
function clearElements() {
$("input[type=text]").val('');
$("select").attr('selectedIndex', 0);
}
In a nutshell, it sets the value of all <input type="text" ... /> elements on the page to an empty string and sets the selectedIndex attribute of all <select> elements on the page to 0. I've created a script on JSFiddle.net to let you try out the script: http://jsfiddle.net/xs6G9/
For More Information
I wrote a blog entry on this topic with more information and discussion. See: Resetting Form Field Values in an ASP.NET WebForm.
Happy Programming!
<input type="reset"> is a simple solution client side.

Refresh updatepanel through triggers when other updatepanel does because the first must have UpdateMode=Conditional

I have some updatepanels in asp.net page. I want updatepanel 2 get refreshed when updatepanel 1 does, but UpdatePanel 2 has his UpdateMode attributed set to Conditional and ChildrenAsTrigger=False, because it has another updatePanels inside and i need to control the way it is refreshed. I was trying to make a trigger for the other updatepanel but this seems not work, maybe i am missing something
Is there a way to make this happen?
If you can't figure a valid example, imagine product category list and product list, when selected category change (linkbutton inside updatepanel) product list is refreshed which is inside another updatepanel, product list change for example when you order by price (order is inside other updatepanel) and i don't want category list gets refreshed.
thanks in advance.
You can call updatePanelProdList.Update() inside the code-behind file of your page. The place to call this method in your scenario would be the event handler for the category change LinkButton.
Thank you, that's what i am looking for! I have 2 "Update Panel" on my page, one keeping my form and other one keeping flexiGrid (non .net version,pure jQuery).
I do manual AsyncPostBack from my grid to get in edit or delete mode.
function doPostBackAsync(eventName, eventArgs) {
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (!Array.contains(prm._asyncPostBackControlIDs, eventName)) {
prm._asyncPostBackControlIDs.push(eventName);
}
if (!Array.contains(prm._asyncPostBackControlClientIDs, eventName)) {
prm._asyncPostBackControlClientIDs.push(eventName);
}
__doPostBack(eventName, eventArgs);
}
<a title="Edit" href="javascript:doPostBackAsync('Edit','2');">Edit</a>
and then i handle it like
string EventName = Request.Form["__EVENTTARGET"].ToString();
int EventValue = Request.Form["__EVENTARGUMENT"].ToString();
after determinate EventName and EventValue calling the method below
protected void Edit(int id)
{
//load the form here
UpdatePanel1.Update(); //do the trick right, without this line unable to show form fields and other stuff with newly loaded data
}
regards.
(sorry for my English)

Passing Listbox Text to Javascript Pop-up Window URL

Is it possible to pass the contents of a textbox or Listbox into the URL portion of the javascript code window.open(URL)? I have an asp.net listbox control that displays URL values. When ever an end user clicks on another listbox, the URL listbox provides the specific URL. I am trying to pass this URL into the above javascript code, but I do not know the correct syntax to do this. This code will execute as an onclick event.
For clarification, similar to typing “+ ListBox.Text.ToString() +” or ‘” & List.Text & “’” to add the content of a listbox into something else, such as a textbox. Is there specific syntax to do the same, but add the listbox.text into javascript?
Thank you,
DFM
Simply add a client-side onclick handler to your listbox as shown below:
<asp:ListBox id="ListBox1" runat="server" .....
onclick="openPopup(this)">
........
</asp:ListBox>
Then add the following javascript code:
<script type="text/javascript">
function openPopup(e){
window.open(e.value);
}
</script>
Sure, this should be pretty easy with jQuery. Obviously the URL generation could be reduced to a single statement, but should give you the general idea.
$(document).ready(function() {
$("your-element").click(function() {
var str = $("#listbox-id").val();
var url = "your-url.com/" + str;
window.open(url);
});
});

Resources