I have a GridView that is filtered by a TextBox. It filters when I leave the control. How do I fire the filter when the TextBox changes?
I set the OnChange event and looked up the value to see if it was at least 3 characters long. If it was I manually called the PostBack:
<asp:TextBox ID="_txtEquipment" runat="server" AutoPostBack="True"
onkeyup="checkforEquipmentNumber();"/>
JavaScript Code:
function checkforEquipmentNumber() {
var txtEquipmentNumber = document.getElementById("_txtEquipment").value;
if (txtEquipmentNumber.length > 2) {
javascript:__doPostBack("_txtEquipment",'');
}
}
I have a complicated page but I created a simple ASP.NET page with the issue. I have telerik RadAsyncUpload control and a button inside an UpdatePanel as shown:
<asp:UpdatePanel ID="_updatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
...
<telerik:RadAsyncUpload ID="fileUpload" runat="server" MaxFileInputsCount="1" OnClientFilesSelected="fileUpload_ClientFilesSelected" /><br />
<asp:Button ID="_saveNewFileButton" runat="server" OnClick="_saveNewFileButton_Click"
Text="Save"/>
</ContentTemplate>
</asp:UpdatePanel>
When a file is selected I want to disable the _saveNewFileButton and change the text to "Please Wait for Attachment Upload..." but I can't seem to get hold of the button reference in javascript:
var FilesUpdateInterval = null;
//Handles client side FilesSelected event for _newFileUploadButton.
function fileUpload_ClientFilesSelected(sender, args) {
//disable the click event for submit button during upload
var submitButton = $find('<%= _saveNewFileButton.ClientID %>');
submitButton.set_text('Please Wait for Attachment Upload...')
submitButton.set_readOnly(true);
if (FilesUpdateInterval == null) {
FilesUpdateInterval = setInterval(function () { FileCheckForUploadCompletion(); }, 500);
}
}
I am getting submitButton is null error. I tried putting this javascript code outside the updatepanel and inside ContentTemplate with same result. Obviously whatever I am doing is wrong. How do I get hold of the control that is in updatepanel in javascript?
EDIT: I find out that $find works with only telerik controls. So, I have to either use document.getElementById function or JQuery with something like Steve specified. Also, I have to use RegisterClientScriptBlock. I will test with Steve suggestion and then accept the answer.
short version - use $get() or document.getElementById(), as regular HTML elements are not IScriptControls, so $find() will not give you anything, and they don't have the rich client API you are trying to use.
For example
var submitButton = $get('<%= _saveNewFileButton.ClientID %>');
submitButton.setAttribute("value", "Please Wait for Attachment Upload...");
Option 2 - use RadButton.
Using jQuery and vb with ASP.Net, I've done something similar to this, which has worked well, even if it isn't that pretty. The [Whatever] I have was a FormView that didn't always have the control. Also, I didn't use it with a button, but I think that's the syntax for changing the button text. Either way, it might give you some ideas:
$('#<%=GetButtonClientID("_saveNewFileButton")%>').attr('value', 'Please Wait for Attachment Upload...');
And then I have a function like this:
Public Function GetButtonClientID(ByVal argFieldName As String) As String
Dim tmpID As String = "0"
Dim tmpButton As Button = [Whatever].FindControl(argFieldName)
If Not tmpButton Is Nothing Then Return tmpButton.ClientID.ToString Else Return "0"
End Function
I've got a asp.net gridview and inside of the grid view I have a check box at the header of the grid view like so:
<HeaderTemplate>
<asp:CheckBox Width="1px" ID="HeaderLevelCheckBox" AutoPostBack="true" OnCheckedChanged="SelectAllRows" runat="server" />
</HeaderTemplate>
This gives me a nice little check box at the top of the grid view...the event OnCheckedChanged calls a function called SelectAllRows that looks like this:
Public Sub SelectAllRows(ByVal sender As Object, ByVal e As System.EventArgs)
Dim gr As GridViewRow = DirectCast(DirectCast(DirectCast(sender, CheckBox).Parent, DataControlFieldCell).Parent, GridViewRow)
Dim h As CheckBox = DirectCast(gr.FindControl("HeaderLevelCheckBox"), CheckBox)
For Each Row As GridViewRow In Me.gvLineItems.Rows
Dim cb As CheckBox = CType(Row.FindControl("chkSelector"), CheckBox)
cb.Checked = h.Checked
Next
End Sub
So if I click this header checkbox it checks all of the items in the gridview, and if I uncheck it, it unchecks all the items in the gridview. This works fine...but what doesnt seem to work is if the page loads up and I check the grid view header checkbox to true and it selects all the items in the gridview, then i click a button such as a DELETE button that calls some server side code. That code simply loops through the grid view and checks if the checkbox has been checked, if it is it calls code to delete an item. Something to this effect:
For Each Row As GridViewRow In Me.gvLineItems.Rows
Dim cb As CheckBox = CType(Row.FindControl("chkSelector"), CheckBox)
Dim lID As Long = Convert.ToInt32(gvLineItems.DataKeys(Row.RowIndex).Value)
If cb IsNot Nothing AndAlso cb.Checked Then
'ok to delete
End If
Next
When I place a watch and debug on this it seems that the value cb is always false...
Even though it was set to true when I clicked the header checkbox...
What gives ???
The actual chkSelector in the grid view is for each row and it looks like this:
<ItemTemplate>
<asp:CheckBox ID="chkSelector" runat="server" onclick="ChangeRowColor(this)" />
</ItemTemplate>
Also I am already checking for postback..that is not the issue, remember chkSelector does not autopostback...
Thanks
I doubt, your gridview is rebinding on a Delete button click, because a click of the Delete button loads the page first where it will rebind and your checkbox's become unchecked again. I think you are binding your gridview some where in the page load event.
You have to do something like this
If(!Page.IsPostBack)
{
//Gridview Binding Code goes here....
}
Edit: Alternatively you can check/uncheck rows using javascript. It will save a round trip to the server side and resolve your current issue as well.
Here is complete code
<script language="javascript" type="text/javascript">
function SelectAll(spanChk,grdClientID) {
var IsChecked = spanChk.checked;
var Chk = spanChk;
Parent = document.getElementById(grdClientID);
var items = Parent.getElementsByTagName('input');
for(i=0;i<items.length;i++)
{
if(items[i].type=="checkbox")
{
items[i].checked=document.getElementById(spanChk).checked;
}
}
}
<HeaderTemplate>
<asp:CheckBox runat="server" ID="chkHeader" onclick="SelectAll('<%=chkHeader.ClientID %>, <%=yourGrid.ClientID %>') />
</HeaderTemplate>
I got a templated control (a repeater) listing some text and other markup. Each item has a radiobutton associated with it, making it possible for the user to select ONE of the items created by the repeater.
The repeater writes the radiobutton setting its id and name generated with the default ASP.NET naming convention making each radiobutton a full 'group'. This means all radiobuttons are independent on each other, which again unfortunately means I can select all radiobuttons at the same time. The radiobutton has the clever attribute 'groupname' used to set a common name, so they get grouped together and thus should be dependant (so I can only select one at a time). The problem is - this doesn't work - the repeater makes sure the id and thus the name (which controls the grouping) are different.
Since I use a repeater (could have been a listview or any other templated databound control) I can't use the RadioButtonList. So where does that leave me?
I know I've had this problem before and solved it. I know almost every ASP.NET programmer must have had it too, so why can't I google and find a solid solution to the problem? I came across solutions to enforce the grouping by JavaScript (ugly!) or even to handle the radiobuttons as non-server controls, forcing me to do a Request.Form[name] to read the status. I also tried experimenting with overriding the name attribute on the PreRender event - unfortunately the owning page and masterpage again overrides this name to reflect the full id/name, so I end up with the same wrong result.
If you have no better solution than what I posted, you are still very welcome to post your thoughts - at least I'll know that my friend 'jack' is right about how messed up ASP.NET is sometimes ;)
ASP.NET Tip: Using RadioButton Controls in a Repeater
This is the code for the JavaScript function:
function SetUniqueRadioButton(nameregex, current)
{
re = new RegExp(nameregex);
for(i = 0; i < document.forms[0].elements.length; i++)
{
elm = document.forms[0].elements[i]
if (elm.type == 'radio')
{
if (re.test(elm.name))
{
elm.checked = false;
}
}
}
current.checked = true;
}
The code is linked to the Repeater through the ItemDataBound event. For it to work properly, you need to know the name of the Repeater control, as well as the GroupName you're assigning to the RadioButtons. In this case, I'm using rptPortfolios as the name of the Repeater, and Portfolios as the group name:
protected void rptPortfolios_ItemDataBound(object sender,
RepeaterItemEventArgs e)
{
if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType
!= ListItemType.AlternatingItem)
return;
RadioButton rdo = (RadioButton)e.Item.FindControl("rdoSelected");
string script =
"SetUniqueRadioButton('rptPortfolios.*Portfolios',this)";
rdo.Attributes.Add("onclick", script);
}
REF: http://www.codeguru.com/csharp/csharp/cs_controls/custom/article.php/c12371/
Google-fu: asp.net radiobutton repeater problem
Indeed an unfortunate consequence of the id mangling. My take would be creating a - or picking one of the many available - custom control that adds support for same name on the client.
Vladimir Smirnov has already created a great custom control that resolves this issue. We have been using the GroupRadioButton in our projects and it has been working perfectly with radio buttons created inside of a repeater and others outside the repeater all being a part of the same group.
I use jQuery script:
<script type="text/javascript">
function norm_radio_name() {
$("[type=radio]").each(function (i) {
var name = $(this).attr("name");
var splitted = name.split("$");
$(this).attr("name", splitted[splitted.length - 1]);
});
};
$(document).ready(function () {
norm_radio_name();
});
// for UpdatePannel
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {
norm_radio_name();
});
</script>
I know this is an old post, but here's what I ended up doing with a listview. My listview is bound in VB codebehind, so I'm not sure if this will work well with a repeater, but I imagine it could be similar.
What I did was handle the OnCheckChanged event of the radiobuttons with a function that unselected any other radio buttons. Then I looked for the selected radio button when I navigated away from the page.
This solution avoids JavaScript and jQuery, and ignores the GroupName issue completely. It's not ideal, but it functions as (I) expected. I hope it's helpful for others.
Markup:
<asp:ListView ID="lvw" runat="server">
<LayoutTemplate>`
<table>
<th>Radio</th>
<tr id="itemPlaceholder"></tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td><asp:RadioButton ID="rdbSelect" runat="server" AutoPostBack="true"
OnCheckedChanged="rdbSelect_Changed"/></td>
</tr>
</ItemTemplate>
</asp:ListView>
Code:
Protected Sub rdbSelect_Changed(ByVal sender As Object, ByVal e As System.EventArgs)
Dim rb1 As RadioButton = CType(sender, RadioButton)
For Each row As ListViewItem In lvw.Items
Dim rb As RadioButton = row.FindControl("rdbSelect")
If rb IsNot Nothing AndAlso rb.Checked Then
rb.Checked = False
End If
Next
rb1.Checked = True
End Sub
And then when the Submit button is clicked:
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
For Each row As ListViewItem In lvw.Items
Dim rb As RadioButton = row.FindControl("rdbSelect")
Dim lbl As Label
If rb IsNot Nothing AndAlso rb.Checked = True Then
lbl = row.FindControl("StudentID")
Session("StudentID") = lbl.Text
End If
Next
Response.Redirect("~/TransferStudent.aspx")
End Sub
This might be a little better..
I have a usercontrol which is essentially a set of radiobuttons inside a repeater, each instance of the usercontrol has a public property called FilterTitle, which is unique per instance.
add these two properties to your radiobutton replacing FilterTitle with your own public property name
onclick='<%# "$(\"input[name$=btngroup_" + FilterTitle + "]\").removeAttr(\"checked\"); $(this).attr(\"checked\",\"checked\");" %>' GroupName='<%# "btngroup_" + FilterTitle %>'
more simply..
onclick="$('input[name$=btngroup1]').removeAttr('checked'); $(this).attr('checked','checked');" GroupName="btngroup1"
Here's a pure Javascript solution for the sake of completeness.
Just add this onclick attribute to your RadioButton element(replace GroupName with your RadioButton's GroupName):
<asp:RadioButton ... GroupName="GroupName" onclick="SelectRadioButton('GroupName$',this)" ... />
And include this Javascript in your page:
<script type="text/javascript">
function SelectRadioButton(regexPattern, selectedRadioButton)
{
regex = new RegExp(regexPattern);
for (i = 0; i < document.forms[0].elements.length; i++)
{
element = document.forms[0].elements[i];
if (element.type == 'radio' && regex.test(element.name))
{
element.checked = false;
}
}
selectedRadioButton.checked = true;
}
</script>
Create a Custom Control and override UniqueID to the listview UniqueID + GroupName
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MYCONTROLS
{
[ToolboxData("<{0}:MYRADIOBUTTON runat=server></{0}:MYRADIOBUTTON >")]
public class MYRADIOBUTTON : RadioButton
{
public override string UniqueID
{
get
{
string uid = base.UniqueID;
//Fix groupname in lisview
if (this.Parent is ListViewDataItem && GroupName != "")
{
uid = this.Parent.UniqueID;
uid = uid.Remove(uid.LastIndexOf('$'));
uid += "$" + GroupName;
}
return uid;
}
}
}
}
It’s a custom control that inherits from RadioButton (public class MYRADIOBUTTON : RadioButton).
If you do nothing in the class you get a normal RadioButton. Overriding the UniqueId you can change the logic for how the name attribute is rendered.
To still keep the name unique to other controls on the page (outside the listview) you can get the UniqueId from the ListView and add GroupName to that and add it to the RadioButton.
This fix the problem with Grouping RadioButtons on different rows in a listview. You may want to add some more logic with a property to turn this feature on/off so it behaves like a normal RadioButton.
I know this question is bit old, but I think it might help somebody, therefore posting my solution to this issue.
This issue has 2 parts:
To prevent selection of more than one radio button at a time.
To know which radio button was clicked in server-side code.
I had the similar issue with Radio button in Repeater. I found partial solution here:
Simple fix for Radio Button controls in an ASP.NET Repeater using jQuery
Please read the above article to get the understanding of the issue. I referred this article and it was good help. As mentioned above this issue has two parts, first is to prevent selection of more than one radio button at a time. Second, to know which radio button was clicked in server-side code. The solution posted in above article worked for me only for the first part. However code written there as well as updates to solution posted there did not work for me. So I had to modify it a bit to get it working. Here is my solution.
I wanted to create poll with Vote button. Name of my radio button (ID) is PollGroupValue with Groupname set to PollGroup in a repeater. Remember Groupname attribute in ASP.net is rendered as name attribute in generated html. My code is as follows:
<script type="text/javascript">
/* Step-01: */
$(document).ready(function () {
/* Step-02: */
$("[name*='PollGroup']").each(function () {
$(this).attr('ci-name', $(this).attr('name'));
});
/* Step-03: */
$("[name*='PollGroup']").attr("name", $("[name*='PollGroup']").attr("name"));
$('#Poll1_BtnVote').click(function (e) {
/* Step - 04: */
if ($("[name*='PollGroup']").filter(':checked').length == 0) {
alert('Please select an option.');
e.preventDefault();
}
/* Step - 05: */
$("[name*='PollGroup']").each(function () {
$(this).attr('name', $(this).attr('ci-name'));
});
});
});
Step 1:
Whenever a radio button is used in repeater, its groupname gets changed, since asp.net changes it so as to make it unique. Therefore each radio button gets different groupname (name attribute in client-side generated markup). Due to this, user is able to select all of the options at the same time. This issue is resolved by using jquery code as explained by subsequent comments.
Step 2:
This block of code creates a new custome attribute called ci-name and copies original value of name attribute into this new custom attribute. This process repeats for every radio button in poll. This step would help us in later step.
Step 3:
This block of code sets the value of name attributes of all radio buttons in poll to the value of name attribute of first radio button. This step prevents user from selecting more than one option at a time.
Step 4:
This code inside event handler of vote button click event, checks whether user has checked at least one option. If he hasn't, an error message is shown.
Step 5:
This code inside event handler of vote button click event, sets value of name attribute of all radio buttons to their original values. This is achieved by copying value from custom attribute ci-name. This allows asp.net server side code to know which button was actually clicked.
I was also baffled by this bug and decided to just drop the repeater in favor of dynamically building a table with the controls inside. In your user control or on your page, simply add the following elements:
<asp:Table ID="theTable" runat="server">
<asp:TableHeaderRow runat="server">
<asp:TableHeaderCell runat="server" Text="Column 1"/>
<asp:TableHeaderCell runat="server" Text="Column 2"/>
<asp:TableHeaderCell runat="server" Text="Column 3"/>
</asp:TableHeaderRow>
</asp:Table>
Then add the data rows in the code behind with radio buttons and other required controls. You can of course do the same with other elements like the DIV:
<div runat="server" ID=theDiv">
</div>
But let us still hope for the ASP.NET team to get around to fixing this unfortunate issue with repeaters and list views. I still like the repeater control and use it whenever possible.
This is a pure server side approach using reflection. The RadioButton control uses the UniqueGroupName property to determine the group name. The group name is cached inside the _uniqueGroupName field. By setting this field using reflection, we can override the default group name and use a group name that is the same across all radio buttons in a repeater. Please note this code must be run in the 'PreRender' event of the 'RadioButton' control to ensure the new group name is persisted across post backs.
protected void rbOption_PreRender(object sender, EventArgs e)
{
// Get the radio button.
RadioButton rbOption = (RadioButton) sender;
// Set the group name.
var groupNameField = typeof(RadioButton).GetField("_uniqueGroupName", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
groupNameField.SetValue(rbOption, "MyGroupName");
// Set the radio button to checked if it was selected at the last post back.
var groupValue = Request.Form["MyGroupName"];
if(rbOption.Attributes["value"] == groupValue)
{
rbOption.Checked = true;
}
}
RadioButton source code: http://reflector.webtropy.com/default.aspx/Net/Net/3#5#50727#3053/DEVDIV/depot/DevDiv/releases/whidbey/netfxsp/ndp/fx/src/xsp/System/Web/UI/WebControls/RadioButton#cs/2/RadioButton#cs
This may not be the ideal solution for everyone, but I did the following using jQuery.
<asp:RadioButton ID="rbtnButton1" groupName="Group1" runat="server" />
<asp:RadioButton ID="rbtnButton2" groupName="Group1" runat="server" />
etc...
Then include the following code in your master page. (or all your pages)
$(function() {
//This is a workaround for Microsoft's GroupName bug.
//Set the radio button's groupName attribute to make it work.
$('span[groupName] > input').click(function() {
var element = this;
var span = $(element).parent();
if (element.checked) {
var groupName = $(span).attr('groupName');
var inputs = $('span[groupName=' + groupName + '] > input')
inputs.each(function() {
if (element != this)
this.checked = false;
});
}
});
});
A custom control/override to work around the HtmlInputControl.RenderAttributes() method by ignoring the RenderedNameAttribute property:
/// <summary>
/// HACK: For Microsoft's bug whereby they mash-up value of the "name" attribute.
/// </summary>
public class NameFixHtmlInputRadioButton : HtmlInputRadioButton
{
protected override void RenderAttributes(HtmlTextWriter writer)
{
// BUG: Usage of 'HtmlInputControl.RenderedNameAttribute'
// writer.WriteAttribute("name", this.RenderedNameAttribute);
writer.WriteAttribute(#"name", Attributes[#"Name"]);
Attributes.Remove(#"name");
var flag = false;
var type = Type;
if (! string.IsNullOrEmpty(type))
{
writer.WriteAttribute(#"type", type);
Attributes.Remove(#"type");
flag = true;
}
base.RenderAttributes(writer);
if (flag && DesignMode)
{
Attributes.Add(#"type", type);
}
writer.Write(#" /");
}
}
I used same Technic to uncheck other radio with jquery please find below code
<asp:RadioButton ID="rbSelectShiptoShop" runat="server" onchange="UnCheckRadio(this);" CssClass="radioShop" />
and script below
function UnCheckRadio(obj) {
$('.radioShop input[type="radio"]').attr('checked', false);
$(obj).children().attr('checked', true);
}
I just want an ASP.NET DropDownList with no selected item. Setting SelectedIndex to -1 is of no avail, so far. I am using Framework 3.5 with AJAX, i.e. this DropDownList is within an UpdatePanel.
Here is what I am doing:
protected void Page_Load (object sender, EventArgs e)
{
this.myDropDownList.SelectedIndex = -1;
this.myDropDownList.ClearSelection();
this.myDropDownList.Items.Add("Item1");
this.myDropDownList.Items.Add("Item2");
}
The moment I add an element in the DropDown, its SelectedIndex changes to 0 and can be no more set to -1 (I tried calling SelectedIndex after adding items as well)... What I am doing wrong? Ant help would be appreciated!
Bare in mind myDropDownList.Items.Add will add a new Listitem element at the bottom if you call it after performing a DataSource/DataBind call so use myDropDownList.Items.Insert method instead eg...
myDropDownList.DataSource = DataAccess.GetDropDownItems(); // Psuedo Code
myDropDownList.DataTextField = "Value";
myDropDownList.DataValueField = "Id";
myDropDownList.DataBind();
myDropDownList.Items.Insert(0, new ListItem("Please select", ""));
Will add the 'Please select' drop down item to the top.
And as mentioned there will always be exactly one Item selected in a drop down (ListBoxes are different I believe), and this defaults to the top one if none are explicitly selected.
I am reading the following:
http://msdn.microsoft.com/en-us/library/a5kfekd2.aspx
It says:
To get the index value of the selected item, read the value of the SelectedIndex property. The index is zero-based. If nothing has been selected, the value of the property is -1.
In the same time, at http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.dropdownlist.selectedindex(VS.80).aspx we see:
Use the SelectedIndex property to programmatically specify or determine the index of the selected item from the DropDownList control. An item is always selected in the DropDownList control. You cannot clear the selection from every item in the list at the same time.
Perhaps -1 is valid just for getting and not for setting the index? If so, I will use your 'patch'.
It's possible to set selectedIndex property of DropDownList to -1 (i. e. clear selection) using client-side script:
<form id="form1" runat="server">
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Value="A"></asp:ListItem>
<asp:ListItem Value="B"></asp:ListItem>
<asp:ListItem Value="C"></asp:ListItem>
</asp:DropDownList>
<button id="СlearButton">Clear</button>
</form>
<script src="jquery-1.2.6.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#СlearButton").click(function()
{
$("#DropDownList1").attr("selectedIndex", -1); // pay attention to property casing
})
$("#ClearButton").click();
})
</script>
I'm pretty sure that dropdown has to have some item selected; I usually add an empty list item
this.myDropDownList.Items.Add("");
As my first list item, and proceed accordingly.
The selectedIndex can only be -1 when the control is first initalised and there is no items within the collection.
It's not possible to have no item selected in a web drop down list as you would on a WinForm.
I find it's best to have:
this.myDropDownList.Items.Add(new ListItem("Please select...", ""));
This way I convey to the user that they need to select an item, and you can check SelectedIndex == 0 to validate
Create your DropDown list and specify an initial ListItem
Set AppendDataBoundItems to true so that new items get appended.
<asp:DropDownList ID="YourID" DataSourceID="DSID" AppendDataBoundItems="true">
<asp:ListItem Text="All" Value="%"></asp:ListItem>
</asp:DropDownList>
Please try below syntax:
DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByValue("Select"))
or
DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByText("SelectText"))
or
DropDownList1.Items.FindByText("Select").selected =true
For more info :
http://vimalpatelsai.blogspot.in/2012/07/dropdownlistselectedindex-1-problem.html