check if button is disabled - c#

I'm working on an application where the users guesses on a number (7 trues). The app contains of an input field as well as a button, and if the user hasn't got more guesses the input field as well as the button is disabled, and a new button appears (restart).
In my code behind-file is the code for checking if the user has more guesses or not, and if not the following code takes care of the disabling/enabling of the buttons:
code behind-file:
...
btnCheckNr.Enabled = false;
inputBox.Enabled = false;
newGame.Visible = true;
...
I'm not using ViewState but Session state, and every time a postpack is done the fields is back as they were from the start, ie. enabled. Every time the user has made a guess the input field gets focus and the content inside (eg. last guess made) gets selected. This works accept for when the field and button gets disabled, and by that reason I've added a check to see if the input field is disabled or not. If so, focus and selection shall not be done (otherwise I get an error).
However, with this code the input field never gets focus, why is that? Is it something that I'm doing wrong and in that case how could this be accomplished?
Thanks in advance!
external.js:
var Capsule = {
init: function() {
var input = $('#inputBox');
if (!input.is(":disabled"))
input.focus();
input.select();
}
}
}
window.onload = Capsule.init;

Try triggering a click instead:
input.click().select();
Demo.

Related

Loading more than one buttons in the same location or not

I am writing a UI interface with user input and buttons. I need to ask the user to input some number and then press the button labelled "solve", which needs to determine whether the number is correct. I try to use only one button to solve it in the beginning. Here is my code:
if (correct)
{
solveButton = new MenuButton(contentManager.Load<Texture2D>("solve"),
buttonCenter, GameState.AnswerNo);
}
else
{
solveButton = new MenuButton(contentManager.Load<Texture2D>("solve"),
buttonCenter, GameState.AnswerYes);
}
When loading it, under the draw method, I use the following code:
solveButton.Draw(spriteBatch);
Here, GameState.AnswerNo and GameState.AnswerYes lead to different pages standing for the correct and incorrect answers, respectively. However, it doesn't work as I thought it would - it always goes to GameState.AnswerNo page no matter the "correct" value is.
Therefore, I am thinking about using two buttons (button figures are the same but move position a little):
solveButton = new MenuButton(contentManager.Load<Texture2D>("solve"),
buttonCenter, GameState.AnswerNo);
buttonCenter.Y -= 40;
solveButton2 = new MenuButton(contentManager.Load<Texture2D>("solve"),
buttonCenter, GameState.AnswerYes);
And when loading them:
if (correct)
{
solveButton.Draw(spriteBatch);
}
if (!correct)
{
solveButton2.Draw(spriteBatch);
}
Which works fine, but the awkward thing is that when the user inputs the correct number, button1 will disappear and button2 will appear just under it. Any better ideas to complete this function?
I think you are looking at the problem wrong.
Instead of using two different buttons, why are you not just using one button, and then set the state via a function?
User inputs value, and presses button.
Button calls function, checks if value is correct.
Based on result, set the active state.

Textbox loses value after postback (ASP - C#)

I've been having a tough time with updating my text boxes and could really use some help. So basically, I have a popup panel for the user to select a value that I then populate into a certain text box.
I am certain that the problem is either very simple to solve, or that I'm confused on what post back actually does. Here is a snippit of my code below:
protected void grvSearchRecords_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (string.Compare(e.CommandName, "EditRow", true) == 0)
{
long nMagic2Value = Convert.ToInt64(e.CommandArgument);
string tmp = GetItem(nMagic2Value, currentTableName);
textBox1.Text = tmp;
Debug.WriteLine(textBox1.Text.ToString());
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "SearchRecords", "$(document).ready(function(){ $('#mask, #divSearchRecordsGrid').fadeOut(\"fast\"); });", true);
}
}
The "tmp" variable grabs the value I need and assigns it to the text box.
I then run a Debug statement and confirm that the value is correctly assigned to the box. As soon as the function ends, however, that assigned value is lost, and the text box never populates with the new value.
Wrap your code around a post back check
if (!IsPostBack)
{
//your code here
}
This will ensure that your code does not run when it is a post back, so your textBox will not be clear.
Post back means that the page is not being rendered for the first time, for example a page refresh.
Okay, I just got it working. The textbox I was trying to change was part of a Content tag and nothing else. I enclosed it in an UpdatePanel and added a trigger for my GridView, and now it works!
The joys of learning a new language.

The last time window popped out overrides those earlier in c#

Not sure My title is correct or not actually.
I have a button, when I click on it, it will pop up a small window (based on data in a repeater) to let the user key-in information and click the OK button to proceed to next step.
Below is my code of the Button.Click :
protected void btnRedeemAll_Click(object sender, EventArgs e)
{
foreach( RepeaterItem itm in repGiftResults.Items )
{
if (pr.AdditionalFieldsEnabled == true)
{
AdditionalInfoGiftProcess(pid, giftId, txtQty, txtToken);
}
}
}
divAdditionalInfo is a division ID, divAdditionalInfo.Style["visibility"] = "visible"; and divAdditionalInfo.Style["display"] = "table-cell"; is to prompt out a window to let user key in information and click on "OK" button to continue :
The following the the code of AdditionalInfoGiftProcess() function :
public void AdditionalInfoGiftProcess(int productID, int giftID, TextBox txtQty, UserControls_TokenControl txtToken)
{
/*
Some logic here
*/
//generate pop up window
divAdditionalInfo.Style["visibility"] = "visible";
divAdditionalInfo.Style["display"] = "table-cell";
}
And below is my code of divAdditionalInfo in html :
<div
id="divAdditionalInfo"
class="BlackCover"
style="VISIBILITY:hidden; DISPLAY:none;" runat="server">
<!--
html code that generate the pop out window.
consist of text box and `OK` button, and "Cancel" button.
-->
</div>
When I click on temoBtn button, I only get 1 time window(div) pop out, means I only can enter 1 time information and click on OK button.
I want the window(div) to pop out 3 times one by one, so that I can key in information for 3 times and click on the OK button 1 by 1.
But, the last time window pop out seen like already override those early pop out window.
Any idea to solve this?
p.s.: Actually you can ignore the html code. It is just a code to generate the pop out window. Means, when I click on tempBtn button, the division with id = "divAdditionalInfo" will prompt out as a window to let the user to key-in info and click on the OK button.
You don't have anything to accept input, in your loop.
All you are doing is setting the visibility 3 times, then moving on.
In your handler for the OK and cancel buttons, you could check for any pending messages and show the next one, if necessary.
What do you want to happen here? When the user clicks OK, should anything happen? Or does the user need to click OK three times in order for the popup to go away?
In any case - as your code stands now, the server is generating a div that is visible. Making it visible once has the same effect as making it visible three times. Once you're by the client, you can try to use JavaScript to force the user to work with the div three times before it will go away.
This doesn't sound like a good situation for the user; maybe consider using separate elements for your three popups?
EDIT:
I'm still not sure how you are setting the style of different elements with your code. Where is the div declared? Inside the template of a repeater? If so - I'm surprised that your code compiles. You would need to loop through the generated template instances of your repeater and call FindControl("divAdditionalInfo") on each of them to get access to each instance of the div.

Force a validation group to fail if a condition isn't met

I have a group of text boxes that have required field validation hooked up to them. Obviously they all share the same validation group name. I have a check box for terms of service that needs to be checked before clicking on the submit button actually does anything.
Is there some C# code that will say if this box isn't checked, fail the validation group?
Or is there a better way?
edit:
I added a custom validator and used this in my code behind. Does not work.
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = false;
if (cbxTerms.Checked)
args.IsValid = true;
}
If I were to do this, I would just use JavaScript. When the page loads, attach a client side event handler to the buttons submit. Inside the handler check to see if the checkbox is checked, if so then return true otherwise return false which should cancel the submit. If JavaScript is turned off then thats OK too because you should have some server side validation happening because people can sumbit forms in other ways as well.
You can do what you did above but with a return if not checked like that
if (!cbxTerms.Checked)
{requiredlabel.text="*";
return;}
You can set a label manually to tell the user that ths field is needed
you can even prevent postback if checkbox is not checked
Button1.Attributes["onclick"] =
"if (!$get('" + CheckBox1.ClientID + "').checked){alert('Agree with us,plz!');return false;}";
why doing all the validation stuff if it can be prevented :)
or if you thurst for forcing group to invalid tou can do it win your own validation on client side:
function myStartUpValidation(group){
var result=true;
//Page_ClientValidate(group); to validate group
for (var i = 0; i < Page_Validators.length; i++) {
if(Page_Validators[i].validationGroup==group){
try{
ValidatorValidate(Page_Validators[i]); //this forces validation in all groups
if(Page_Validators[i].isvalid==false){result=false;}
}catch(err){}
}
}
return result;
}
or an extra validator...
Scott Mitchell had an article on this.
https://web.archive.org/web/20211020153238/https://www.4guysfromrolla.com/articles/121907-1.aspx
https://web.archive.org/web/20210304131838/https://www.4guysfromrolla.com/articles/092006-1.aspx
I think it's a slightly different approach, but I used it a while ago to handle a similar situation and it seemed to work pretty well.
I figured out how to do it. I made a textbox, assigned a req field validator to it. Put the textbox 99999px off the screen. In my c# i said if the check box is checked, the textbox.text = ""; in the checkbox check changed event I said if the check box is checked then the textbox.text = "1";. Much easier than any other solution I could find
Edit: Better to use a hidden field.

How can I remove the input focus from textbox?

I'm making simple C# Winform application. There is a Form having a textbox. I want to change the location of textbox by arrow key but textbox has the input focus so form's KeyDown event is not called. How can I remove that input focus?
Typing on the textbox should still be possible. I try to make a dummy label and give the focus, but It doesn't work. If I press any key, the cursor go back to the textbox. please help me. How can I solve this problem?
Handle the TextBox.KeyDown event. And set e.Handled = true; in your handler after you move the TextBox, but before you return. And, yeah, only handle the arrow keys.
Hmm, not sure if I understand. If the user can type into the edit box, then it can have focus. If he clicks outside of it, on a blank are of the form, then it loses focus.
If you want to be able to 1) type into the edit box and 2) move the edit box, then you need a separate mechanism to enter "move mode".
I would suggest either a "click here to move selected control" button, or a right-click context menu on the control with a "move control option".
You would also have to conisder how the user indicates that moving has ended.
Hope this helps.
NOTE: I just realized this is not even an in-browser C# app. I guess disregard all of this. Serves me right for not reading carefully enough.
Use Javascript, in particular, I'd personally recommend jQuery.
They have pretty nicely documented their library: http://docs.jquery.com/Main_Page
For this particular task, you are going to want to bind some sort of key event (ie. keypress) and make sure to stop event propagation (so that you prevent the default response which is to be sent to be simply handled by the textbox element's default listener).
So, to give you an idea, if you want to change the location of the textbox using keypresses (maybe arrow keys), do something like this:
/* link the jQuery source to the HTML page with script tag */
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
/* short hand for $(document).ready(function() { ... */
$(function() {
$("#textbox_id").keypress(function(e) {
var $this = $(this); // store the #textbox_id element in $this
e.preventDefault();
switch (e.keyCode) {
// find the actual integer code for the up arrow
case UP_ARROW:
$this.animate({
top : '-=10px'
}, 100); // time in milliseconds to complete the animation
/* fill in the cases */
}
}
});
Okay, I hope you get the picture. Find out more about animate() and other jQuery functions at in the documentation at the link I provided above. Hope that helps!
NOTE: Obviously, preventing the default handling of events is a terrible idea in this case for accessibility reasons. Use your best judgement when selecting keypresses to trigger these moving events -- whatever you do, don't disallow users from moving around within the text they have in input fields.

Categories

Resources