Autofill feature with Listbox in asp.net - 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.

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);
}

Returning Arraylist from recursive function for ASP.Net

Please refer the attached screenshot. I have an array of the checkbox and a button for the post back in ASP.Net page. I have written a function as follows to determine what all check boxes have been checked on the button click event: The following code is a part of the business component which is called from ASP.Net. Please let me know how can I return actionArray back to calling functon in ASP.Net page.
public void checkBoxValidation(Control parent, string strKey)
{
XmlDocument getCyleXML = new XmlDocument();
string strChkID="", strActionXPath = "",strAction="";
ArrayList actionArray = new ArrayList();
// Loop through all the controls on the page
foreach (Control c in parent.Controls)
{
// Check and see if it's a checkbox.
if ((c.GetType() == typeof(CheckBox)))
{
// Since its a checkbox, see if this is checked.
if (((CheckBox)(c)).Checked == true)
{
// Find the ID of the checkbox
strChkID = ((CheckBox)(c)).ID.ToString();
getCyleXML = CycleXML(strKey);
strActionXPath = "/Actions/Action[checkbox='" + strChkID + "']/*[self::Name]";
strAction = getCyleXML.SelectSingleNode(strActionXPath).ToString();
actionArray.Add(strAction);
}
}
// Now we need to call itself (recursion) because all items (Panel, GroupBox, etc) is a container so we need to check
// all containers for any checkboxes.
if (c.HasControls())
{
checkBoxValidation(c, strKey);
}
}
}
The code should be like this :
public ArrayList checkBoxValidation(Control parent, string strKey, ArrayList actionArray)
{
XmlDocument getCyleXML = new XmlDocument();
string strChkID="", strActionXPath = "",strAction="";
if(actionArray == null) { actionArray = new ArrayList(); }
// Loop through all the controls on the page
foreach (Control c in parent.Controls)
{
// Check and see if it's a checkbox.
if ((c.GetType() == typeof(CheckBox)))
{
// Since its a checkbox, see if this is checked.
if (((CheckBox)(c)).Checked == true)
{
// Find the ID of the checkbox
strChkID = ((CheckBox)(c)).ID.ToString();
getCyleXML = CycleXML(strKey);
strActionXPath = "/Actions/Action[checkbox='" + strChkID + "']/*self::Name]";
strAction = getCyleXML.SelectSingleNode(strActionXPath).ToString();
actionArray.Add(strAction);
}
}
// Now we need to call itself (recursion) because all items (Panel, GroupBox, etc) is a container so we need to check
// all containers for any checkboxes.
if (c.HasControls())
{
checkBoxValidation(c, strKey, actionArray);
}
}
return actionArray;
}

Rebind a RadGrid from a RadWindow

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);
}
}
}
}

Why my yui datatable within an updatepanel disappears after postback?

I got my YUI datatable rendered with my json datasource inside an updatepanel... If i click a button within that updatepanel causes postback and my yui datatable disappears
Why yui datatable within an updatepanel disappears after postback?
EDIT:
I am rendering YUI Datatable once again after each post back which is not a form submit... I know it is a bad practice...
What can be done for this.... Any suggestion.....
if (!IsPostBack)
{
GetEmployeeView();
}
public void GetEmployeeView()
{
DataTable dt = _employeeController.GetEmployeeView().Tables[0];
HfJsonString.Value = GetJSONString(dt);
Page.ClientScript.RegisterStartupScript(Page.GetType(), "json",
"EmployeeDatatable('" + HfJsonString.Value + "');", true);
}
When i click any button in that page it causes postback and i have to
regenerate YUI Datatable once again with the hiddenfield value containing
json string..
protected void LbCancel_Click(object sender, EventArgs e)
{
HfId.Value = "";
HfDesigId.Value = "";
ScriptManager.RegisterClientScriptBlock(LbCancel, typeof(LinkButton),
"cancel", "EmployeeDatatable('" + HfJsonString.Value + "');, true);
}
My javascript:
function EmployeeDatatable(HfJsonValue){
var myColumnDefs = [
{key:"Identity_No", label:"Id", width:50, sortable:true, sortOptions:{defaultDir:YAHOO.widget.DataTable.CLASS_DESC}},
{key:"Emp_Name", label:"EmployeeName", width:150, sortable:true, sortOptions:{defaultDir:YAHOO.widget.DataTable.CLASS_DESC}},
{key:"Address", label:"Address", width:200, sortable:true, sortOptions:{defaultDir:YAHOO.widget.DataTable.CLASS_DESC}},
{key:"Desig_Name", label:"Category", width:200, sortable:true, sortOptions:{defaultDir:YAHOO.widget.DataTable.CLASS_DESC}},
{key:"", formatter:"checkbox"}
];
var jsonObj=eval('(' + HfJsonValue + ')');
var target = "datatable";
var hfId = "ctl00_ContentPlaceHolder1_HfId";
generateDatatable(target,jsonObj,myColumnDefs,hfId)
}
function generateDatatable(target,jsonObj,myColumnDefs,hfId){
var root;
for(key in jsonObj){
root = key; break;
}
var rootId = "id";
if(jsonObj[root].length>0){
for(key in jsonObj[root][0]){
rootId = key; break;
}
}
YAHOO.example.DynamicData = function() {
var myPaginator = new YAHOO.widget.Paginator({
rowsPerPage: 10,
template: YAHOO.widget.Paginator.TEMPLATE_ROWS_PER_PAGE,
rowsPerPageOptions: [10,25,50,100],
pageLinks: 10 });
// DataSource instance
var myDataSource = new YAHOO.util.DataSource(jsonObj);
myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
myDataSource.responseSchema = {resultsList: root,fields:new Array()};
myDataSource.responseSchema.fields[0]=rootId;
for(var i=0;i<myColumnDefs.length;i++){
myDataSource.responseSchema.fields[i+1] = myColumnDefs[i].key;
}
// DataTable configuration
var myConfigs = {
sortedBy : {key:myDataSource.responseSchema.fields[1], dir:YAHOO.widget.DataTable.CLASS_ASC}, // Sets UI initial sort arrow
paginator : myPaginator
};
// DataTable instance
var myDataTable = new YAHOO.widget.DataTable(target, myColumnDefs, myDataSource, myConfigs);
myDataTable.subscribe("rowMouseoverEvent", myDataTable.onEventHighlightRow);
myDataTable.subscribe("rowMouseoutEvent", myDataTable.onEventUnhighlightRow);
myDataTable.subscribe("rowClickEvent", myDataTable.onEventSelectRow);
myDataTable.subscribe("checkboxClickEvent", function(oArgs){
var hidObj = document.getElementById(hfId);
var elCheckbox = oArgs.target;
var oRecord = this.getRecord(elCheckbox);
var id=oRecord.getData(rootId);
if(elCheckbox.checked){
if(hidObj.value == ""){
hidObj.value = id;
}
else{
hidObj.value += "," + id;
}
}
else{
hidObj.value = removeIdFromArray(""+hfId,id);
}
});
myPaginator.subscribe("changeRequest", function (){
if(document.getElementById(hfId).value != "")
{
if(document.getElementById("ConfirmationPanel").style.display=='block')
{
document.getElementById("ConfirmationPanel").style.display='none';
}
document.getElementById(hfId).value="";
}
return true;
});
myDataTable.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
oPayload.totalRecords = oResponse.meta.totalRecords;
return oPayload;
}
return {
ds: myDataSource,
dt: myDataTable
};
}();
}
Hai guys,
I got an answer for my qusetion.... Its my postback that caused the problem and i solved it by making an ajax call using ajax enabled WCF Service in my web application... Everything works fine now....
Anything you are generating client side will have to be regenerated after every page refresh (and after every partial page refresh, if that part contains client-side generated html).
Because the YUI datatable gets its data on the client, you will have to render it again each time you replace that section of html.

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