Convert controls dynamically from strings - asp.net

I want to disable some controls on my asp page from a ControlCollection.
This is my code.
foreach (System.Web.UI.Control c in ControlCollection)
{
if (c.GetType().FullName.Equals("System.Web.UI.WebControls.Table"))
{
TableRow t = (TableRow)c;
t.Enabled = false;
}
else if (c.GetType().FullName.Equals("System.Web.UI.WebControls.TextBox"))
{
TextBox t = (TextBox)c;
t.Enabled = false;
}
.......
......
///Like this I do for all controls
}
I need a better approach at this. I searched on Internet but didn't find any solution.

You can use the .OfType<> extension like this in order to have more elegant code:
collection.OfType<Table>().ToList().ForEach(c => c.Enabled = false);
collection.OfType<TextBox>().ToList().ForEach(c => c.Enabled = false)

Do all controls in your list inherit from System.Web.UI.WebControl? If so, than this code may help. (Didn't test it myself)
Type wc = new System.Web.UI.WebControls.WebControl(HtmlTextWriterTag.A).GetType();
foreach (System.Web.UI.Control c in ControlCollection)
{
if (c.GetType().IsSubclassOf(wc))
{
((System.Web.UI.WebControls.WebControl)c).Enabled = false;
}
}
And even more elegant (thanx to Shadow Wizard )
ControlCollection.OfType<System.Web.UI.WebControls.WebControl>().ToList().ForEach(c => c.Enabled = false);

Try to use is.
if (c is Table)
{
}
else if (c is TextBox)
{
}
Or consider doing a switch statement on the type name.
switch (c.GetType().Name.ToLower())
{
case "table":
break;
case "textbox":
break;
}

Related

Hiding fields in Quick View form with JS not working

I need to hide few fields in a Quick View Form based on an Option Set (Choice) selection in that Quick View form. However it is not working, so am sharing the code I used for the same here. In my code, I am trying to hide certain fields if the option selected is not equal to a particular value...
function hideFields(executionContext) {
var formContext = executionContext.getFormContext();
var quickViewControl = formContext.ui.quickForms.get("General");
if (quickViewControl != undefined) {
if (quickViewControl.isLoaded()) {
var orgtypevalue = quickViewControl.getControl("new_organizationtype").getValue();
if (orgtypevalue != 248870006) {
quickViewControl.getControl("new_recipienttype").setVisible(false);
quickViewControl.getControl("new_businesstype").setVisible(false);
quickViewControl.getControl("new_businesstypecode").setVisible(false);
quickViewControl.getControl("new_businesstypecharacteristicstypecode").setVisible(false);
return;
}
else {
// Wait for some time and check again
setTimeout(getAttributeValue, 10, executionContext);
}
}
else {
console.log("No data to display in the quick view control.");
return;
}
else {
quickViewControl.getControl("new_recipienttype").setVisible(true);
quickViewControl.getControl("new_businesstype").setVisible(true);
quickViewControl.getControl("new_businesstypecode").setVisible(true);
quickViewControl.getControl("new_businesstypecharacteristicstypecode").setVisible(true);
return;
}
}
}
I need to know where am I wrong. Any help will be appreciated.
Thanks!
you need to update the following
first if version 9 I am updating this
"var quickViewControl = formContext.ui.quickForms.get("General");"
to "var quickViewControl = formContext._ui._quickForms.get("General");"
&
"var orgtypevalue = quickViewControl.getControl("new_organizationtype").getValue();"
to
"var orgtypevalue = quickViewControl.getAttribute("new_organizationtype").getValue();"
& update else with message to wait and call the function again like this
"setTimeout(hideFields, 10, executionContext);"
and add else for the If of "quickViewControl != undefined"
Kindly find the updated code:
function hideFields(executionContext) {
var formContext = executionContext.getFormContext();
var quickViewControl = formContext._ui._quickForms.get("General");
if (quickViewControl != undefined) {
if (quickViewControl.isLoaded()) {
var orgtypevalue = quickViewControl.getAttribute("new_organizationtype").getValue();
if (orgtypevalue != 248870006) {
quickViewControl.getControl("new_recipienttype").setVisible(false);
quickViewControl.getControl("new_businesstype").setVisible(false);
quickViewControl.getControl("new_businesstypecode").setVisible(false);
quickViewControl.getControl("new_businesstypecharacteristicstypecode").setVisible(false);
return;
}
else {
// Wait for some time and check again
setTimeout(hideFields, 10, executionContext);
}
}
else {
//console.log("No data to display in the quick view control.");
//return;
setTimeout(hideFields, 10, executionContext);
}
}
}

X++ passing current selected records in a form for your report

I am trying to make this question sound as clear as possible.
Basically, I have created a report, and it now exists as a menuitem button so that the report can run off the form.
What I would like to do, is be able to multi-select records, then when I click on my button to run my report, the current selected records are passed into the dialog form (filter screen) that appears.
I have tried to do this using the same methods as with the SaleLinesEdit form, but had no success.
If anyone could point me in the right direction I would greatly appreciate it.
Take a look at Axaptapedia passing values between forms. This should help you. You will probably have to modify your report to use a form for the dialog rather than using the base dialog methods of the report Here is a good place to start with that!
Just wanted to add this
You can use the MuliSelectionHelper class to do this very simply:
MultiSelectionHelper selection = MultiSelectionHelper::createFromCaller(_args.caller());
MyTable myTable = selection.getFirst();
while (myTable)
{
//do something
myTable = selection.getNext();
}
Here is the resolution I used for this issue;
Two methods on the report so that when fields are multi-selected on forms, the values are passed to the filter dialog;
private void setQueryRange(Common _common)
{
FormDataSource fds;
LogisticsControlTable logisticsTable;
QueryBuildDataSource qbdsLogisticsTable;
QueryBuildRange qbrLogisticsId;
str rangeLogId;
set logIdSet = new Set(Types::String);
str addRange(str _range, str _value, QueryBuildDataSource _qbds, int _fieldNum, Set _set = null)
{
str ret = _range;
QueryBuildRange qbr;
;
if(_set && _set.in(_Value))
{
return ret;
}
if(strLen(ret) + strLen(_value) + 1 > 255)
{
qbr = _qbds.addRange(_fieldNum);
qbr.value(ret);
ret = '';
}
if(ret)
{
ret += ',';
}
if(_set)
{
_set.add(_value);
}
ret += _value;
return ret;
}
;
switch(_common.TableId)
{
case tableNum(LogisticsControlTable):
qbdsLogisticsTable = element.query().dataSourceTable(tableNum(LogisticsControlTable));
qbrLogisticsId = qbdsLogisticsTable.addRange(fieldNum(LogisticsControlTable, LogisticsId));
fds = _common.dataSource();
for(logisticsTable = fds.getFirst(true) ? fds.getFirst(true) : _common;
logisticsTable;
logisticsTable = fds.getNext())
{
rangeLogId = addrange(rangeLogId, logisticsTable.LogisticsId, qbdsLogisticsTable, fieldNum(LogisticsControlTable, LogisticsId),logIdSet);
}
qbrLogisticsId.value(rangeLogId);
break;
}
}
// This set the query and gets the values passing them to the range i.e. "SO0001, SO0002, SO000£...
The second methods is as follows;
private void setQueryEnableDS()
{
Query queryLocal = element.query();
;
}
Also on the init method this is required;
public void init()
{
;
super();
if(element.args() && element.args().dataset())
{
this.setQueryRange(element.args().record());
}
}
Hope this helps in the future for anyone else who has the issue I had.

How to know which value items where selected from a CheckBoxList using Request.Form?

How to get which value items where selected from a CheckBoxList using Request.Form?
I see these 2 form keys:
[12]: "ctl00$MainContent$cblTimeOfDay$0"
[13]: "ctl00$MainContent$cblTimeOfDay$3"
0 and 3 are the selected values from my check box list which has 4 items.
I'd need to find those values programmaticlaly on Page_Init
thanks,
I'm not sure about accessing these via the Request.Form. Can't you access the strongly-typed CheckBoxList control itself? This article provides a simply method that accepts a CheckBoxList and returns all the selected values; you may update this to return a reference to the selected item, or any other specifics you require:
public string[] CheckboxListSelections(System.Web.UI.WebControls.CheckBoxList list)
{
ArrayList values = new ArrayList();
for(int counter = 0; counter < list.Items.Count; counter++)
{
if(list.Items[counter].Selected)
{
values.Add(list.Items[counter].Value);
}
}
return (String[]) values.ToArray( typeof( string ) );
}
So, within your Page_Init event handler, call like so:
var selectedValues = CheckboxListSelections(myCheckBoxList);
Where myCheckBoxList is a reference to your CheckBoxList control.
I wrote this method which works but not with the best performance:
public static TimeOfDay Create(NameValueCollection httpRequestForm, string checkBoxId)
{
var result = new TimeOfDay();
var selectedCheckBoxItems = from key in httpRequestForm.AllKeys
where key.Contains(checkBoxId)
select httpRequestForm.Get(key);
if (selectedCheckBoxItems.Count() == 0)
{
result.ShowFull = true;
return result;
}
foreach (var item in selectedCheckBoxItems)
{
var selectedValue = int.Parse(item.Substring(item.Length));
switch (selectedValue)
{
case 0:
result.ShowAm = true;
break;
case 1:
result.ShowPm = true;
break;
case 2:
result.ShowEvening = true;
break;
case 3:
result.ShowFull = true;
break;
default:
throw new ApplicationException("value is not supported int the check box list.");
}
}
return result;
}
and use it like this:
TimeOfDay.Create(this.Request.Form, this.cblTimeOfDay.ID)

Cannot Access the Controls inside an UpdatePanel

What I am trying to do is accessing Page Controls at Page_Load, and make a database query, and make controls visible or not visible.
Here is the Code:
foreach (Control thiscontrol in ContentPlaceHolderBody.Controls) {
try {
if (thiscontrol.ID.Contains("TextBox") || thiscontrol.ID.Contains("Label")) {
string dummy = thiscontrol.ID;
bool IsValid = db.Roles.Any(a => a.controlName == dummy);
if (IsValid == false)
thiscontrol.Visible = false;
}
else if (thiscontrol.ID.Contains("UpdatePanel")) {
foreach (Control UPcontrols in ((UpdatePanel)thiscontrol).ContentTemplateContainer.Controls) {
if (UPcontrols.ID.Contains("TextBox") || UPcontrols.ID.Contains("DropDownList")) {
bool UPIsValid = db.Roles.Any(a => a.controlName == UPcontrols.ID);
if (UPIsValid == false)
UPcontrols.Visible = false;
}
}
}
}
catch { }
}
My Problem is with the UPcontrols! It should retrieve the controls within the UpdatePanel, but the thing is it doesn't do its job, except in the debug mode!
When I add a breakpoint, everything is OK, but when I run the web application, it doesn't find any components within the UpdatePanel...
Try this one:
ControlCollection cbb = updatepanel1.Controls;
ControlCollection cb = cbb[0].Controls;
initialize_Controls(cb);
public void initialize_Controls(ControlCollection objcontrls)
{
foreach (Control tb in objcontrls) {
if (tb is TextBox)
((TextBox)tb).Text = "";
if (tb is Panel) {
ControlCollection cbcll = tb.Controls;
foreach (Control tbb in cbcll) {
if (tbb is TextBox)
((TextBox)tbb).Text = "";
}
}
}
}
First find controls from updatepanel i.e ContentTemplate, then find controls from contentTemplate which contain all controls in it.
This seems like a very bizarre design. That is, using control IDs for such purposes is rather unusual.
Nevertheless, you need a recursive method here to do a deep walk of every control on the page. Your method will not work if the UpdatePanel is contained within another control.
Have a check on this article
http://www.codeproject.com/Articles/24178/The-magical-effects-of-the-UpdatePanel-control-in

How to combine similar JavaScript methods to one

I have an ASP.NET code-behind page linking several checkboxes to JavaScript methods. I want to make only one JavaScript method to handle them all since they are the same logic, how would I do this?
Code behind page load:
checkBoxShowPrices.Attributes.Add("onclick", "return checkBoxShowPrices_click(event);");
checkBoxShowInventory.Attributes.Add("onclick", "return checkBoxShowInventory_click(event);");
ASPX page JavaScript; obviously they all do the same thing for their assigned checkbox, but I'm thinking this can be reduced to one method:
function checkBoxShowPrices_click(e) {
if (_hasChanged) {
confirm(
'All changes will be lost. Do you wish to continue?',
function(arg) {
if (arg.toUpperCase() == 'YES') {
var checkBox = document.getElementById('<%=checkBoxShowPrices.UniqueID%
>');
checkBox.checked = !checkBox.checked;
eval("<%=base.GetPostBackEventReference(checkBoxShowPrices)%>");
_hasChanged = false;
}
});
return false;
} else {
eval("<%=base.GetPostBackEventReference(checkBoxShowPrices)%>");
}
}
function checkBoxShowInventory_click(e) {
if (_hasChanged) {
confirm(
'All changes will be lost. Do you wish to continue?',
function(arg) {
if (arg.toUpperCase() == 'YES') {
var checkBox = document.getElementById('<%
=checkBoxShowInventory.UniqueID%>');
checkBox.checked = !checkBox.checked;
eval("<%=base.GetPostBackEventReference(checkBoxShowInventory)%>");
_hasChanged = false;
}
});
return false;
} else {
eval("<%=base.GetPostBackEventReference(checkBoxShowInventory)%>");
}
}
Add to the event the checkbox that is raising it:
checkBoxShoPrices.Attributes.Add("onclick", "return checkBox_click(this, event);");
Afterwards in the function you declare it like this:
function checkBoxShowPrices_click(checkbox, e){ ...}
and you have in checkbox the instance you need
You can always write a function that returns a function:
function genF(x, y) {
return function(z) { return x+y*z; };
};
var f1 = genF(1,2);
var f2 = genF(2,3);
f1(5);
f2(5);
That might help in your case, I think. (Your code-paste is hard to read..)

Resources