Rebind a RadGrid from a RadWindow - asp.net

I have in my main aspx page a RadGrid which allows the user to open a RadWindow when they click on a picture (within the RadGrid).
When I close my RadWindow I need to rebind my RadGrid. The problem is I'm not in the same page. Thus, I don't have access to the RadGrid in my RadWindow page.
Is there any way to add instructions within CloseDialog to rebind the RadGrid?
This is the code I'm using to close the RadWindow.
function GetRadWindow() {
var oWindow = null;
if (window.radWindow) oWindow = window.radWindow;
else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow;
return oWindow;
}
function CloseDialog() {
GetRadWindow().close();
return true;
}

Try this:
In radWindow you will get one client event called OnClientClose, you can call that window and rebind your grid easily. See below what i have done:
<telerik:RadWindow runat="server" Behaviors="Maximize,Close,Move" ID="editorWindow"
VisibleStatusbar="false" Width="800px" ReloadOnShow="true" ShowContentDuringLoad="false"
OnClientClose="OnWindowClose" Modal="true" Height="500px" />
Here is the JS Function :
function OnWindowClose(sender, eventArgs) {
var MasterTable = gridID.get_masterTableView();
MasterTable.rebind();
}
Note: on pageLoad of parent page i have assigned the gridID like this var gridID = $find('<%=radGrid.ClientID%>'). You can also find/get the grid directly in OnWindowClose function as my scenario was bit different.

You can also fire itemcommand for particular row using below code.
function ClientClose(oWnd, args) {
if (oWnd != null && oWnd.get_name() == "checkwindowname") {
var grid = $find("<%=Radgrid1.ClientID %>");
if (grid) {
var MasterTable = grid.get_masterTableView();
var Rows = MasterTable.get_dataItems();
for (var i = 0; i < Rows.length; i++) {
var row = Rows[i];
// put your codition here if you want
MasterTable.fireCommand("YourCommandName", i);
}
}
}
}

Related

GridView is scrolling back to top after In-Row Button Click

I have a GridView inside an UpdatePanel. The GridView (GV) contains In-Row Buttons. If the GV list is very long and press the Buttons on the bottom rows, the page scrolls to the top and I cannot find which button I had clicked.
I have tried, MaintainScrollPositionOnPostback="true", but since I am using an UpdatePanel, this does not seem to be working.
I would like the screen to remain on the Row where I have clicked the Button.
set UpdatePanel UpdateMode="Always"
add this function:
public static string GetPostBackControlId(Page page)
{
Control control = null;
// first we will check the "__EVENTTARGET" because if post back made by the controls
// which used "_doPostBack" function also available in Request.Form collection.
string controlName = page.Request.Params["__EVENTTARGET"];
if (!String.IsNullOrEmpty(controlName))
{
control = page.FindControl(controlName);
}
else
{
// if __EVENTTARGET is null, the control is a button type and we need to
// iterate over the form collection to find it
// ReSharper disable TooWideLocalVariableScope
string controlId;
Control foundControl;
// ReSharper restore TooWideLocalVariableScope
foreach (string ctl in page.Request.Form)
{
// handle ImageButton they having an additional "quasi-property"
// in their Id which identifies mouse x and y coordinates
if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
{
controlId = ctl.Substring(0, ctl.Length - 2);
foundControl = page.FindControl(controlId);
}
else
{
foundControl = page.FindControl(ctl);
}
if (!(foundControl is Button || foundControl is ImageButton)) continue;
control = foundControl;
break;
}
}
return control == null ? String.Empty : control.ID;
}
use this in page_loadto get postback controlId:
if (IsPostBack)
{
string controlName = GetPostBackControlId(this);
}

Autofill feature with Listbox in asp.net

i have a Listbox with items being 'first name' loaded from a table of a database,
now i want an autofill feature where if a user types like 'a' all the names starting with 'a' first name should be show in the listbox
and after some button click the original data should be repopulated in the listbox
for 2nd one i.e.. repopulating hope i can do with below code
protected void btnRePopulate_Click(object sender, EventArgs e)
{
DataSet oDs = ReadDataSet();
Listbox1.DataTextField = "Name";
Listbox1.DataValueField = "ID";
Listbox1.DataSource = oDs;
Listbox1.DataBind();
}
but for the 1st i have some things on which iam working (i am using textbox keyup event to fire when the user types 'a' or whatever)
clear the listbox and add the names which starts with 'a', but not sure is it possible from client side
or set another listbox visible with names filtered from the original and hide the original listbox, for which i am not able to set visible property either from js or codebehind
no i dont want to use ajax autofill
is there a better option apart from the above two...
This filtering and resetting is best done on the client side itself. That way you don't make unnecessary server calls. Here is a extension method in jQuery.
$(function() {
$('#select').filterByText($('#textbox'), true);
});
Extension method:
jQuery.fn.filterByText = function(textbox, selectSingleMatch) {
return this.each(function() {
var select = this;
var options = [];
$(select).find('option').each(function() {
options.push({value: $(this).val(), text: $(this).text()});
});
$(select).data('options', options);
$(textbox).bind('change keyup', function() {
var options = $(select).empty().scrollTop(0).data('options');
var search = $.trim($(this).val());
var regex = new RegExp(search,'gi');
$.each(options, function(i) {
var option = options[i];
if(option.text.match(regex) !== null) {
$(select).append(
$('<option>').text(option.text).val(option.value)
);
}
});
if (selectSingleMatch === true &&
$(select).children().length === 1) {
$(select).children().get(0).selected = true;
}
});
});
};
I found this on Lessan Vaezi's blog with a live demo on how to do it.

Problem with a button's OnClientClick event inside an UpdatePanel

im using javascript like
var TargetBaseControl = null;
window.onload = function()
{
try
{
//get target base control.
TargetBaseControl =
document.getElementById('<%= this.GridView1.ClientID %>');
}
catch(err)
{
TargetBaseControl = null;
}
}
function TestCheckBox()
{
if(TargetBaseControl == null) return false;
//get target child control.
var TargetChildControl = "chkSelect";
//get all the control of the type INPUT in the base control.
var Inputs = TargetBaseControl.getElementsByTagName("input");
for(var n = 0; n < Inputs.length; ++n)
if(Inputs[n].type == 'checkbox' &&
Inputs[n].id.indexOf(TargetChildControl,0) >= 0 &&
Inputs[n].checked)
return true;
alert('Select at least one checkbox!');
return false;
}
and inside the update panel i have code like
<asp:Button ID="ButtonSave" runat="server" OnClick="ButtonSave_Click"
OnClientClick="javascript:return TestCheckBox();" Text="Save" />
when i run the page and click the button then no more further processing just button has been click nothing happan......
Try this:
function TestCheckBox()
{
var TargetBaseControl = null;
if(TargetBaseControl = document.getElementById('<%= this.GridView1.ClientID %>')){
//get target child control.
var TargetChildControl = "chkSelect";
//get all the control of the type INPUT in the base control.
var Inputs = TargetBaseControl.getElementsByTagName("input");
for(var n = 0; n < Inputs.length; ++n)
if(Inputs[n].type == 'checkbox' &&
Inputs[n].id.indexOf(TargetChildControl,0) >= 0 &&
Inputs[n].checked)
return true;
}
alert('Select at least one checkbox!');
return false;
}
look at the source of your page once it is in a browser.
see what happens with the OnClientClick assignment.
does it get rewritten/re-routed ?
it should be pretty clear at that point.
you can also step through with tools such as Firebug in firefox, IE8 developer tools, chrome developer tools, or visual studio

Change textbox's css class when ASP.NET Validation fails

How can I execute some javascript when a Required Field Validator attached to a textbox fails client-side validation? What I am trying to do is change the css class of the textbox, to make the textbox's border show red.
I am using webforms and I do have the jquery library available to me.
Here is quick and dirty thing (but it works!)
<form id="form1" runat="server">
<asp:TextBox ID="txtOne" runat="server" />
<asp:RequiredFieldValidator ID="rfv" runat="server"
ControlToValidate="txtOne" Text="SomeText 1" />
<asp:TextBox ID="txtTwo" runat="server" />
<asp:RequiredFieldValidator ID="rfv2" runat="server"
ControlToValidate="txtTwo" Text="SomeText 2" />
<asp:Button ID="btnOne" runat="server" OnClientClick="return BtnClick();"
Text="Click" CausesValidation="true" />
</form>
<script type="text/javascript">
function BtnClick() {
//var v1 = "#<%= rfv.ClientID %>";
//var v2 = "#<%= rfv2.ClientID %>";
var val = Page_ClientValidate();
if (!val) {
var i = 0;
for (; i < Page_Validators.length; i++) {
if (!Page_Validators[i].isvalid) {
$("#" + Page_Validators[i].controltovalidate)
.css("background-color", "red");
}
}
}
return val;
}
</script>
You could use the following script:
<script>
$(function(){
if (typeof ValidatorUpdateDisplay != 'undefined') {
var originalValidatorUpdateDisplay = ValidatorUpdateDisplay;
ValidatorUpdateDisplay = function (val) {
if (!val.isvalid) {
$("#" + val.controltovalidate).css("border", "2px solid red");
}
originalValidatorUpdateDisplay(val);
}
}
});
</script>
This code decorates the original ValidatorUpdateDisplay function responsible for updating the display of your validators, updating the controltovalidate as necessary.
Hope this helps,
I think you would want to use a Custom Validator and then use the ClientValidationFunction... Unless it helpfully adds a css class upon fail.
Some time ago I spend a few hours on it and since then I have been using some custom js magic to accomplish this.
In fact is quite simple and in the way that ASP.NET validation works. The basic idea is add a css class to attach a javascript event on each control you want quick visual feedback.
<script type="text/javascript" language="javascript">
/* Color ASP NET validation */
function validateColor(obj) {
var valid = obj.Validators;
var isValid = true;
for (i in valid)
if (!valid[i].isvalid)
isValid = false;
if (!isValid)
$(obj).addClass('novalid', 1000);
else
$(obj).removeClass('novalid', 1000);
}
$(document).ready(function() {
$(".validateColor").change(function() {validateColor(this);});
});
</script>
For instance, that will be the code to add on an ASP.Net textbox control. Yes, you can put as many as you want and it will only imply add a CssClass value.
<asp:TextBox ID="txtBxEmail" runat="server" CssClass="validateColor" />
What it does is trigger ASP.Net client side validation when there is a change on working control and apply a css class if it's not valid. So to customize visualization you can rely on css.
.novalid {
border: 2px solid #D00000;
}
It's not perfect but almost :) and at least your code won't suffer from extra stuff. And
the best, works with all kind of Asp.Net validators, event custom ones.
I haven't seen something like this googling so I wan't to share my trick with you. Hope it helps.
extra stuff on server side:
After some time using this I also add this ".novalid" css class from code behind when need some particular validation on things that perhaps could be only checked on server side this way:
Page.Validate();
if (!requiredFecha.IsValid || !CustomValidateFecha.IsValid)
txtFecha.CssClass = "validateColor novalid";
else
txtFecha.CssClass = "validateColor";
Here is my solution.
Advantages over other solutions:
Integrates seamlessly with ASP.NET - NO changes required to code. Just call the method on page load in a master page.
Automatically changes the CSS class when the text box or control changes
Disadvantages:
Uses some internal features of ASP.NET JavaScript code
Tested only on ASP.NET 4.0
HOW TO USE:
Requires JQuery
Call the "Validation_Load" function when the page loads
Declare a "control_validation_error" CSS class
function Validation_Load() {
if (typeof (Page_Validators) != "object") {
return;
}
for (var i = 0; i < Page_Validators.length; i++) {
var val = Page_Validators[i];
var control = $("#" + val.controltovalidate);
if (control.length > 0) {
var tagName = control[0].tagName;
if (tagName != "INPUT" && tagName != "TEXTAREA" && tagName != "SELECT") {
// Validate sub controls
}
else {
// Validate the control
control.change(function () {
var validators = this.Validators;
if (typeof (validators) == "object") {
var isvalid = true;
for (var k = 0; k < validators.length; k++) {
var val = validators[k];
if (val.isvalid != true) {
isvalid = false;
break;
}
}
if (isvalid == true) {
// Clear the error
$(this).removeClass("control_validation_error");
}
else {
// Show the error
$(this).addClass("control_validation_error");
}
}
});
}
}
}
}
Alternatively, just iterate through the page controls as follows: (needs a using System.Collections.Generic reference)
const string CSSCLASS = " error";
protected static Control FindControlIterative(Control root, string id)
{
Control ctl = root;
LinkedList<Control> ctls = new LinkedList<Control>();
while ( ctl != null )
{
if ( ctl.ID == id ) return ctl;
foreach ( Control child in ctl.Controls )
{
if ( child.ID == id ) return child;
if ( child.HasControls() ) ctls.AddLast(child);
}
ctl = ctls.First.Value;
ctls.Remove(ctl);
}
return null;
}
protected void Page_PreRender(object sender, EventArgs e)
{
//Add css classes to invalid items
if ( Page.IsPostBack && !Page.IsValid )
{
foreach ( BaseValidator item in Page.Validators )
{
var ctrltoVal = (WebControl)FindControlIterative(Page.Form, item.ControlToValidate);
if ( !item.IsValid ) ctrltoVal.CssClass += " N";
else ctrltoVal.CssClass.Replace(" N", "");
}
}
}
Should work for most cases, and means you dont have to update it when you add validators. Ive added this code into a cstom Pageclass so it runs site wide on any page I have added validators to.

Jquery get Selected Radio Button from List on page load

I was wondering if anyone can post an example of how to get a selected radio button option from an asp.net radio button list control via jquery on the loading of a page.
Thanks
In your javascript function where you want to query the list, use this code..
var selected = jQuery('#<%= MyRadioButtonList.ClientID %> input:checked').val();
// or ...
var selected = $('#<%= MyRadioButtonList.ClientID %> input:checked').val();
to set a sample label with the results of your selected radiobuttonlist, you could do this...
$(document).ready(function(){
var selected = $('#<%= MyRadioButtonList.ClientID %> input:checked').val();
$("#<%= MySampleLabel.ClientID %>").text(selected);
}
Working example here.
The selector I used to get the radio buttons will grab all the radio buttons with the class ofinterest on the page.
$(function(){
var value = $('input.ofinterest:checked').val();
$('#result').text(value);
});
If you want to scope the selector further, and you don't mind writing your JS directly in your aspx/ascx, you can use Scott's solution above instead. But if you give the buttons you're interested in a known classname, you can put this JS in a .js file.
protected void radioButton_CheckedChanged(object sender, EventArgs e)
{
throw new ApplicationException("Radio Changed");
RadioButton rb = (RadioButton)sender;
TextBox tbexact = (TextBox)this.UpdatePanel1.FindControl("TextBoxExact");
TextBox tbpartial = (TextBox)this.UpdatePanel1.FindControl("TextBoxPartial");
DropDownList dropdown = (DropDownList)this.UpdatePanel1.FindControl("DropDownListCountries");
RadioButton rbc = (RadioButton)this.UpdatePanel1.FindControl("RadioButtonExact");
if (tbexact == null)
throw new ApplicationException("Could not find control");
else
throw new ApplicationException("Found it");
if (rbc != null && rb.Equals(rbc))
{
tbpartial.Enabled = false;
dropdown.Enabled = false;
mCriteria = SearchCriteria.Exact;
}
rbc = (RadioButton)this.UpdatePanel1.FindControl("RadioButtonPartial");
if (rbc != null && rb.Equals(rbc))
{
tbexact.Enabled = false;
dropdown.Enabled = false;
mCriteria = SearchCriteria.Partial;
}
rbc = (RadioButton)this.UpdatePanel1.FindControl("RadioButtonPerCountry");
if (rbc != null && rb.Equals(rbc))
{
tbexact.Enabled = false;
tbpartial.Enabled = false;
mCriteria = SearchCriteria.Country;
}
}

Resources