Hide aspx button in code behind - asp.net

I am trying to hide an aspx button on page load if another element has a certain value.
Button:
<input type="button" class="formButton" id="btnShowTerminate" value="Terminate Credential" onclick="ToggleTerminationRow()">
My issue is that I don't know how to edit the buttons attributes (to make it hidden) in the code behind.

In code behind (on PageLoad event):
Page.btnShowTerminate.Visible = false;

HTML controls need to be given the runat="server" attribute in order to be used in the server-side code.
To hide the button from your code behind, use an If statement to test if your 'other element' has the required value.
C#
If(exampleElement.Value == "example value")
{
Page.btnShowTerminate.Visible = false;
}
VB
If exampleElement.Value == "example value"
Page.btnShowTerminate.Visible = false;
End If
This error -
'System.Web.UI.Page' does not contain a definition for
'btnShowTerminate' and no extension method 'btnShowTerminate'
accepting a first argument of type 'System.Web.UI.Page' could be found
(are you missing a using directive or an assembly reference?
is because you haven't included runat="server" in your input.
The exampleElement.Value may have to be different depending on what type of element exampleElement is. For example, Value will work with a TextBox , but you would need to use InnerHtml for a div

Although, a button (any control for that matter) can be hidden from code behind by setting the Visible property to false, there is subtle, and dangerous nuance to that. Doing this causes the button not only to be hidden, but the resulting HTML button will not render on the page. Should you have JavaScript that is referencing the button, the JavaScript will fail because the button does not exist on the rendered page. In debugging, the bug will be caught, but if the JavaScript is never exercised until the code is deployed to a server, it will fail there but no exception will be thrown. The code just won't work and there will be no indication as to why!
The safe way to hide the button is setting the Style as follows:
btnName.Style.Add("display", "none");
This way the button will be rendered but hidden and JavaScript will be able to find it.

Related

how to display checkboxes on read-only form (ASP.NET)

I have a read-only form filled out automatically from a database. I have several fields with true/false values, and would like them displayed as checkboxes that are either empty or checked. I can databind the checkbox control and disable it, but then it appears grayed out. Is there a simple way to change this so it will show up at a normal, easy-to-read boldness but still be disabled? If not, what's the best way to do this? Should I use an image?
You can go like this as well.
<asp:CheckBox id="checkbox1" Text="Custom" onclick="javascript: return false;" />
Which will render it as
<input type="checkbox"
checked onclick="javascript: return false;">Custom</input>
Interesting question!
There's only one issue I can see with using images instead of normal checkboxes, and that's how the active checkboxes will differ from the disabled (image-based) checkboxes. So, if you go the image route, you will probably want to style all checkboxes. :)
You can effectively disable any checkbox with the following jQuery method (I've only tested in Chrome and IE 9, so far).
$('.readonly:checkbox').click(function(e) {
e.preventDefault();
});
This will "disable" any checkbox with the "readonly" class.
Or, you can use an inline JavaScript function (albiet not recommended, as it adds clutter and confusion):
<input type="checkbox" onclick="event.preventDefault();" />
The reason you would use "preventDefault()" instead of "return false", is because returning false will stop propagation. This means that your click event will not bubble to the parent element. That could potentially cause problems with other code... but it's unlikely.
Also, like Bala R mentioned, you mustn't rely on these restrictions to work. Your server side code should be aware that these values are read only, and refrain from updating them.
Here is jsFiddle example: http://jsfiddle.net/xixionia/3rXCB/
I hope this is helpful! :)
You can do something like this with javascript and use it for the checkbox's onclick handler.
jsFiddle link
function makeMeReadonly(checkbox){
checkbox.checked = !checkbox.checked;
}
and
<asp:CheckBox id="checkbox1" onclick="makeMeReadonly(this)" />
or
<asp:CheckBox id="checkbox1" onclick="this.checked = !this.checked" />
if you want it inline.
but you shouldn't depend on this for security as it will be a regular check box when javascript is not available and/or client code is not that difficult to work around client code restrictions but in your case since you have a readonly view, I wouldn't think you have any logic to save changes.
I just had the same problem and fixed it with an OnClick event on the checkbox. In the event handler the .Checked state is set to the value it is supposed to display.
private void chkBox_CheckStateChanged(object sender, EventArgs e)
{
chkBox.Checked = boolDatabasevalue;
return;
}
Works great, the user can click on the checkbox but the check mark does not change.
The only issue is a slight border shadow indicating the Focus. But the checkmark is, as OP was looking for, of easy-to-read boldness.
NB: this is C#, but in Asp.Net this should work similarly.

Control is set to visible false, jQuery selector fails

Hi I have some controls on an asp.net modal which I show manually via code behind. Now I am trying to attach a selector on one of the controls inside pageLoad(), problem being is that the modal container is initially set to visible=false.
I tried checking for length but it still throws exception
if ($('#<%= myControl.ClientId %>').length > 0)
{
$('#<%= myControl.ClientID %>').click(function() {
// Do work
});
}
Compiler Error Message: CS0103: The name 'myControl' does not exist in the current context
A few things here, the first/main issue is that myControl isn't defined in the current scope, wherever you are in ASP.Net, that's entirely a .Net side problem.
For the Script, there are more issues, .ClientID, not .ClientId. Also, there's no need to check for it's existence, you can just do:
$('#<%=myControl.ClientID%>').click(function(){
// Do work
});
...if the control isn't there, it just won't find/bind anything. There's also an easier way to go about it in ASP.Net, if there's a unique class you can give it, just give add that class, e.g. CssClass="MyClass", then use that as your selector; like this:
$('.MyClass').click(function(){
// Do work
});
This allows you to put the script in an external file instead of the page as well, another benefit to the user.

Problem with access to control properties in Multibox

I used multibox-component to create lightbox-similar div. But I faced problem. I placed textbox with id ‘tbx_position’ in that div. I entered some symbols in textbox and then tried to read value via javascript-function (it had to alert document.getElementById(‘tbx_position’).value). Every time that value was empty.
There is example of it.
Furthermore, if I place in the div asp:Button, server OnClick-eventhandler doesn’t catch fire.
Is any idea, what’s reason? Thanks.
Try adding the <form> & </form> tags to your page.

Is there a way to use Thickbox with dynamic content?

Here's the scenario:
I have a textbox and a button on a web page. When the button is clicked, I want a popup window to open (using Thickbox) that will show all items that match the value entered in the textbox. I am currently using the IFrame implementation of Thickbox. The problem is that the URL to show is hardcoded into the "alt' attribute of the button. What I really need is for the "alt" attribute to pass along the value in the textbox to the popup.
Here is the code so far:
<input type="textbox" id="tb" />
<input alt="Search.aspx?KeepThis=true&TB_iframe=true&height=500&width=700" class="thickbox" title="Search" type="button" value="Search" />
Ideally, I would like to put the textbox value into the Search.aspx url but I can't seem to figure out how to do that. My current alternative is to use jQuery to set the click function of the Search button to call a web service that will set some values in the ASP.NET session. The Search.aspx page will then use the session variables to do the search. However, this is a bit flaky since it seems like there will always be the possibility that the search executes before the session variables are set.
Just handle the onclick of your button to run a function that calls tb_show(), passing the value of the text box. Something like
... onclick = "doSearch()" ...
function doSearch()
{
tb_show(caption, 'Search.aspx?KeepThis=true&q=\"' +
$('input#tb').val() +
'\"&TB_iframe=true&height=500&width=700');
}
If you read the manual, under the iframe content section, it tells you that your parameters need to go before the TB_iframe parameter. Everything after this gets stripped off.
Here is an idea. I don't think it is very pretty but should work:
$('input#tb').blur(function(){
var url = $('input.thickbox').attr('alt');
var tbVal = $(this).val();
// add the textbox value into the query string here
// url = ..
$('input.thickbox').attr('alt', url);
});
Basically, you update the button alt tag every time the textbox loses focus. Instead, you could also listen to key strokes and update after every one.
As far as updateing the query string, I'll let you figure out the best way. I can see putting a placeholder in there like: &TB=TB_PLACEHOLDER. Then you can just do a string replace.
In the code-behind you could also just add the alt tag progammatically,
button1.Attributes.Add("alt", "Search.aspx?KeepThis=true&TB_iframe=true&height=500&width=700");

Setting Focus with ASP.NET AJAX Control Toolkit

I'm using the AutoComplete control from the ASP.NET AJAX Control Toolkit and I'm experiencing an issue where the AutoComplete does not populate when I set the focus to the assigned textbox.
I've tried setting the focus in the Page_Load, Page_PreRender, and Page_Init events and the focus is set properly but the AutoComplete does not work. If I don't set the focus, everything works fine but I'd like to set it so the users don't have that extra click.
Is there a special place I need to set the focus or something else I need to do to make this work? Thanks.
We had exactly the same problem. What we had to do is write a script at the bottom of the page that quickly blurs then refocuses to the textbox. You can have a look at the (terribly hacky) solution here: http://www.drive.com.au
The textbox id is MainSearchBox_SearchTextBox. Have a look at about line 586 & you can see where I'm wiring up all the events (I'm actually using prototype for this bit.
Basically on the focus event of the textbox I set a global var called textBoxHasFocus to true and on the blur event I set it to false. The on the load event of the page I call this script:
if (textBoxHasFocus) {
$get("MainSearchBox_SearchTextBox").blur();
$get("MainSearchBox_SearchTextBox").focus();
}
This resets the textbox. It's really dodgy, but it's the only solution I could find
this is waste , its simple
this is what you need to do
controlId.focus(); in C#
controlID.focus() in VB
place this in page load or button_click section
eg. panel1.focus(); if panel1 has model popup extender attached to it, then we put this code in page load section
How are you setting focus? I haven't tried the specific scenario you've suggested, but here's how I set focus to my controls:
Public Sub SetFocus(ByVal ctrl As Control)
Dim sb As New System.Text.StringBuilder
Dim p As Control
p = ctrl.Parent
While (Not (p.GetType() Is GetType(System.Web.UI.HtmlControls.HtmlForm)))
p = p.Parent
End While
With sb
.Append("<script language='JavaScript'>")
.Append("function SetFocus()")
.Append("{")
.Append("document.")
.Append(p.ClientID)
.Append("['")
.Append(ctrl.UniqueID)
.Append("'].focus();")
.Append("}")
.Append("window.onload = SetFocus;")
.Append("")
.Append("</script")
.Append(">")
End With
ctrl.Page.RegisterClientScriptBlock("SetFocus", sb.ToString())
End Sub
So, I'm not sure what method you're using, but if it's different than mine, give that a shot and see if you still have a problem or not.
What I normally do is register a clientside script to run the below setFocusTimeout method from my codebehind method. When this runs, it waits some small amount of time and then calls the method that actually sets focus (setFocus). It's terribly hackish, but it seems you have to go a route like this to stop AJAX from stealing your focus.
function setFocusTimeout(controlID) {
focusControlID = controlID;
setTimeout("setFocus(focusControlID)", 100);
}
function setFocus() {
document.getElementById(focusControlID).focus();
}
I found the answers from Glenn Slaven and from Kris/Alex to get me closer to a solution to my particular problem with setting focus on an ASP.NET TextBox control that had an AutoCompleteExtender attached. The document.getElementById(focusControlID).focus() kept throwing a javascript error that implied document.getElementById was returning a null object. The focusControlID variable was returning the correct runtime ClientID value for the TextBox control. But for whatever reason, the document.getElementById function didn't like it.
My solution was to throw jQuery into the mix, as I was already using it to paint the background of any control that had focus, plus forcing the Enter key to tab through the form instead of firing a postback.
My setFocus function ended up looking like this:
function setFocus(focusControlID) {
$('#' + focusControlID).blur();
$('#' + focusControlID).focus();
}
This got rid of the javascript runtime error, put focus on the desired TextBox control, and placed the cursor within the control as well. Without first blurring then focusing, the control would be highlighted as if it had focus, but the cursor would not be sitting in the control yet. The user would still have to click inside the control to begin editing, which would be an UX annoyance.
I also had to increase the timeout from 100 to 300. Your mileage my vary...
I agree with everyone that this is a hack. But from the end-user's perspective, they don't see this code. The hack for them is if they have to manually click inside the control instead of just being automatically placed inside the control already and typing the first few letters to trigger the auto lookup functionality. So, hats off to all who provided their hacks.
I hope this is helpful to someone else.

Resources