How to disable button if textbox is empty - c#

First of all sorry for my bad english.
I'm beginner at C# and i made a Windows forms application but i can't disable one button if a textbox is empty.
I tried some of the Enabled methods but they didn't work. Hope someone can help me fix this. Thank you very much
public partial class ModulusForm : Form
{
public double nje;
public double dy;
public double pergjigja;
public double rezultati;
public ModulusForm()
{
InitializeComponent();
Button btn = new Button();
btn.Click += new EventHandler(butoniGjenero_Click);
}
private void butoniPerfundo_Click(object sender, EventArgs e)
{
this.Close();
}
private void butoniGjenero_Click(object sender, EventArgs e)
{
Random random = new Random();
nje = random.Next(1, 100);
dy = random.Next(1, 100);
if (nje > dy)
{ textboxPyetja.Text = "X = " + nje + " " + "dhe" + " " + "Y = " + dy; }
else if (nje > dy)
{
nje = random.Next(1, 100);
dy = random.Next(1, 100);
}
rezultati = nje / dy;
}
private void butoniPastro_Click(object sender, EventArgs e)
{
textboxPyetja.Clear();
textboxPergjigja.Clear();
textboxPergjigjaSakt.Clear();
}
private void butoniVerteto_Click(object sender, EventArgs e)
{
try
{
pergjigja = double.Parse(textboxPergjigja.Text);
}
catch
{
var informim = MessageBox.Show("Rishiko fushat!", "Verejtje", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
if (textboxPergjigja.Text == "")
{
//nothin' baby
}
else
{
if (textboxPyetja.Text == "")
{
var informim = MessageBox.Show("Fusha e pyetjes eshte null!", "Verejtje", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
if (pergjigja == rezultati)
{
textboxPergjigjaSakt.Text = "Pergjigja eshte e sakte";
}
else
{
textboxPergjigjaSakt.Text = "Gabim." + " " + "Pergjigja e sakte eshte: " + "" + rezultati;
}
comboboxVargu.Items.Add(nje + " / " + dy + " = " + rezultati);
}
}
}
}
}

Credit to #Cody Gray for already suggesting this; I have just expanded it, so you can see how to implement and how it works
Overview
You can wire up an event handler for when your textboxPergjigja.Text's text has changed.
In the handler you create, you can then evaluate whether your button should be Enabled or not - using the string.IsNullOrWhiteSpace() check to set this.
First:
In your constructor for the form, subscribe to the textboxPergjigja.Text text box's TextChanged event.
Like this:
public ModulusForm()
{
InitializeComponent();
Button btn = new Button();
btn.Click += new EventHandler(butoniGjenero_Click);
// Add the subscription to the event:
textboxPergjigja.TextChanged += textboxPergjigja_TextChanged;
}
Next:
Add a handler that matches the correct delegate signature for that event.
Like this:
public textboxPergjigja_TextChanged(object sender, TextChangedEventArgs e)
{
// If the text box is not "empty", it will be enabled;
// If the text is "empty", it will be disabled.
butoniVerteto.Enabled = !string.IsNullOrWhiteSpace(textBoxPergjigja.Text);
}
This way, whenever the text in the textBoxPergjigja text box is changed; the evaluation is run and your button will always be enabled/disabled correctly.
Hope this helps! :)
Additional Info
You can also use textBox.Text.IsNullOrEmpty(), and it will still work - as suggested by #Cody
I have used string.IsNullOrWhiteSpace(), as opposed to textBox.Text.IsNullOrEmpty() for the following reasons:
The .IsNullOrEmpty() method only checks if the textBox.Text is either null or the total amount of characters is equal to 0.
The problem this might pose is, if the user only enters a space in the textbox, it is no longer Empty or null; thus this check will return true. If the logic of the program requires that an actual value be entered into the textbox, this logic can be flawed.
On the other hand: The string.IsNullOrWhiteSpace() check will check on 3 conditions - if the input string is null, Empty and contains only whitespace characters (space, newline etc.), also.
I hope this adds a little bit of extra fluff to give you an informed decision for future.

Hope it work!
private void YourTextBox_TextChanged(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(YourTextBox.Text))
YourButton.Enabled = false;
else
YourButton.Enabled = true;
}

Handle it on TextChanged event of your TextBox. (double click on your textbox control when in designed, which will automatically create the text changed event for you).
private void textboxPyetja_OnTextChanged(..blah blah)
{
if(String.IsNullOrWhitespace(txtTargetTextbox.Text)
{
//disable your control
}
else
{
//enable your control
}
}
Edit after 4 years - for some reason:
And here's a one-liner version, some people just love them...
private void textboxPyetja_OnTextChanged(..blah blah)
{
btnILoveButtons.Enabled = string.IsNullOrWhitespace(txtTargetTextbox.Text);
{

Try this:
if (String.IsNullOrEmpty(textboxPergjigja.Text))
butoniVerteto.Enabled = false;
else
butoniVerteto.Enabled = true;

add an event for edit text in the txtbox. when the text changes, enable the button

Change textBox1 for your textbox name then change button1 name for you button name
if (textBox1.Text == "")
{
button1.Enabled = false;
}
else
button1.Enabled = true;

Related

Button.Enabled not working on first of several buttons in BackgroundWorker

I have several buttons that I want turned off/on at different times. I put these into a function for simplicity. Enabling the buttons is called by a BackgroundWorker so that I can update a camera view at the same time as listening to a Serial port for an 'enable' signal. Disabling the controls is called by the button click, while enable is handled by the BackgroundWorker (it watches for the Serial port signal). All buttons re-enable, except for the first one listed in enableControls();. If I change the order of enableControls() then the button at top is left disabled. What is causing this? I would think that either all buttons or no buttons would be re-enabled.
private void btnLeft_Click(object sender, EventArgs e) // All buttons are similar, just different output to port
{
disableControls();
hardWorker.RunWorkerAsync();
int stepSize = Convert.ToInt32(ddStepSize.Text);
string outString;
if (moveSampHome == false)
{
outString = "#MOVER" + stepSize;
posX = posX - RcDrawSlide.Width * stepSize / (1000 * Convert.ToInt32(slideSizeX));
}
else { outString = "#MSMPR" + stepSize; }
port.Write(outString + "\n");
}
private void hardWorker_DoWork(object sender2, DoWorkEventArgs f)
{
arduinoIn = "0";
for (int i = 0; i == 0;)
{
if (arduinoIn != null)
{
if (arduinoIn.Contains("1"))
{
i = 1;
arduinoIn = "0";
}
}
}
port.Write("1");
}
private void hardWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
enableControls();
}
private void enableControls()
{
btnBack.Enabled = true; // Swap this for any other button - that one will not be enabled.
btnForward.Enabled = true;
btnLeft.Enabled = true;
btnRight.Enabled = true;
}
private void disableControls()
{
btnBack.Enabled = false;
btnForward.Enabled = false;
btnLeft.Enabled = false;
btnRight.Enabled = false;
}
If I add a button that runs enableControls() on click everything is reenabled, so I know this is due to having it run from a BackgroundWorker. I think that BackgroundWorker is necessary, though. I'm just unsure why it's only the first btn.Enabled = true; that doesn't work. Is there a workaround for this?
For hardWorker_DoWork() try something more like:
private void hardWorker_DoWork(object sender2, DoWorkEventArgs f)
{
arduinoIn = "0";
while (arduino == null || !arduinoIn.Contains("1")) {
System.Threading.Thread.Sleep(0); // or try a SMALL number like 50!
}
arduinoIn = "0";
port.Write("1");
}
Is it possible the buttons are being enabled again when data is received on the port? You haven't shown any code relating to that side...

TextBox : Modify user's input

When the user adds a ;, I want to add ; + Environment.NewLine in the TextBox.
I find this solution :
private void TextBox_OnPreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (e.Text == ";")
{
e.Handled = true;
TextCompositionManager.StartComposition(
new TextComposition(InputManager.Current,
(IInputElement)sender,
";" + Environment.NewLine)
);
}
}
But after this, the undo don't work.
Can you explain me how control the user input and keep the undo stack?
-------------- Updated Code As Requested ---------
Use this Instead and 100% it's work. I test it for assurance.
private void TextBox_OnPreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (e.Text == ";")
{
// In this line remove preview event to preventing event repeating
((TextBox)sender).PreviewTextInput -= TextBox_OnPreviewTextInput;
// Whith this code get the current index of you Caret(wher you inputed your semicolon)
int index = ((TextBox)sender).CaretIndex;
// Now do The Job in the new way( As you asked)
((TextBox)sender).Text = ((TextBox)sender).Text.Insert(index, ";\r\n");
// Give the Textbox preview Event again
((TextBox)sender).PreviewTextInput += TextBox_OnPreviewTextInput;
// Put the focus on the current index of TextBox after semicolon and newline (Updated Code & I think more optimized code)
((TextBox)sender).Select(index + 3, 0);
// Now enjoy your app
e.Handled = true;
}
}
Wish you bests , Heydar
Thank to Heydar for the solution.
I applied some improvements :
private void TextBox_OnPreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (e.Text == ";")
{
var textBox = (TextBox) sender;
var selectStart = textBox.SelectionStart;
var insertedText = ";" + Environment.NewLine;
// In this line remove preview event to preventing event repeating
textBox.PreviewTextInput -= TextBox_OnPreviewTextInput;
// Now do The Job
textBox.Text = textBox.Text.Insert(selectStart, insertedText);
// Give the TextBox preview Event again
textBox.PreviewTextInput += TextBox_OnPreviewTextInput;
// Put the focus after the inserted text
textBox.Select(selectStart + insertedText.Length, 0);
// Now enjoy your app
e.Handled = true;
}
}

How do I reset random number, count, text, and label with button click c# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am using Visual C# 2013. I have a form and I am wondering how to make my "Clear" button reset/refresh the whole form to the same state when I first clicked start (random number generated at form load, counter, textbox, and a label). For a number guessing form so that a user can play it again. Thanks in advance. Code is :
{
int Answer; // declares the Answer variable outside button event
int Guesses = 0; // start counter outside button event
int UserGuess;
public frmGuess()
{ // generates random number outside button event so does not change on button click
InitializeComponent();
Random rand = new Random();
Answer = rand.Next(100) + 1; // makes it range 1 to 100
}
private void btnGuess_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtGuess.Text)) // input validation check to make sure not blank
{
MessageBox.Show("Please enter a whole number between 1 and 100", "Error!!");
return;
} //end if
if (txtGuess.Text != "") // if its not blank, check to make sure its a whole number with try-catch
{
try
{
UserGuess = int.Parse(txtGuess.Text);
}
catch
{
MessageBox.Show("Please enter a whole number between 1 and 100", "Error!!");
}
} // end if
else
UserGuess = int.Parse(txtGuess.Text); // variable assign and code run
Guesses ++;
if (UserGuess > Answer)
{
txtGuess.Text = "";
lblAnswer.Text = "Too high, try again.";
Guesses++;
}
else if (UserGuess < Answer)
{
txtGuess.Text = "";
lblAnswer.Text = "Too low, try again.";
Guesses++;
}
else
{
lblAnswer.Text = "Congratulations the answer was " + Answer + "!\nYou guessed the number in " + Guesses + " tries.\nTo play again click the clear button.";
} //end if
}
private void btnClear_Click(object sender, EventArgs e) // clears Answer label and Guess textbox
{
txtGuess.Text = "";
lblAnswer.Text = "";
}
private void btnExit_Click(object sender, EventArgs e) // closes window
{
this.Close();
}
}
Here is a screenshot when they have guessed the number! (I don't have enough rep to post an image yet) http://i.stack.imgur.com/hB9yV.png
First, you should put all of the "initialization to be reset" code into a method that can be shared by the constructor and the "Clear" button:
private void ResetForm()
{
txtGuess.Text = "";
lblAnswer.Text = "";
Random rand = new Random();
Answer = rand.Next(100) + 1;
Guesses = 0;
}
(aside: you can actually just initialize the rand object once, as a readonly member field of the class (it can even be static if you like)...but in this case creating a new Random object each time you want to choose a new number, though not the most elegant approach, will work fine).
Then, call that method from your constructor and from the Click event handler:
public frmGuess()
{
InitializeComponent();
ResetForm();
}
private void btnClear_Click(object sender, EventArgs e)
{
ResetForm();
}
By the way, your "Guess" button handler could use some work too:
private void btnGuess_Click(object sender, EventArgs e)
{
lblAnswer.Text = "";
if (string.IsNullOrEmpty(txtGuess.Text)) // input validation check to make sure not blank
{
MessageBox.Show("Please enter a whole number between 1 and 100", "Error!!");
return;
} //end if
if (!int.TryParse(txtGuess.Text, out UserGuess))
{
MessageBox.Show("Please enter a whole number between 1 and 100", "Error!!");
return;
}
Guesses ++;
if (UserGuess > Answer)
{
txtGuess.Text = "";
lblAnswer.Text = "Too high, try again.";
}
else if (UserGuess < Answer)
{
txtGuess.Text = "";
lblAnswer.Text = "Too low, try again.";
}
else
{
lblAnswer.Text = "Congratulations the answer was " + Answer + "!\nYou guessed the number in " + Guesses + " tries.\nTo play again click the clear button.";
} //end if
}
The above removes some redundant code, fixes at least one bug, and gets rid of the need for exception handling.
EDIT
First, check out if you didn't drop brackets around if (txtGuess.Text != "") ... else(here) first.
private void btnClear_Click(object sender, EventArgs e) // clears Answer label and Guess textbox
{
txtGuess.Text = ""; // to reset the TextBox
lblAnswer.Text = ""; // to reset the Label
Random rand = new Random(); // Doesn't it make Answer to be always the same integer?
Answer = rand.Next(100) + 1; // to generate a new random answer
Guesses = 0; // to reset the number of guesses
}
Just try InitializeComponent(); inside the callback of Button_Click.
try reset control :
foreach (Control ctl in this.Controls)
{
ctl.ResetText();
}

keyboard input in calculator in c# and managing the cursor

I am making a calculator. I want it to take input from the keyboard too. this is a portion of my code. The problem is that at the second input from keyboard the + sign doesn't go, it appends with the "+" sign and while input from button click it doesn't show + sign. and tell me is it right to make a function for both button click and key press or i should make separate for each? and how to manage cursor in textbox?
private void button1_Click(object sender, EventArgs e)
{
yourArithmeticOperation = true; //Enable Arithmetic button click
yourEqual = true; //Enable Equal button click
if (yourNumberControl) //check number button to append or start new
{
if (yourControlClick) //check click button enabled or not
{
textBox1.Text += "1"; //append no.
}
else
return;
}
else
{
textBox1.Text = "1"; //clear textbox and put new no.
yourNumberControl = true; //Enable Number button click
}
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Add)
{
add();
}
}
private void add()
{
yourEqual = false; //Disable equal button
yourNumberControl = true; //enable number button
if (yourArithmeticOperation) //check Arithmetic button
{
num1 = double.Parse(textBox1.Text);
textBox1.Text = "";
equal = "+";
yourArithmeticOperation = false; // disable arithmetic operator
}
else //change the arithmeetic sign
{
textBox1.Text = "";
equal = "+";
}
}

Cancel/Clear button event Post Back And Trying To Validate Fields

this is driving me crazy.
I have a piece of code on a Windows Form Control, this code ensures the form clears and put the focus back to the first Control (Phone Number). The problem is I am using On-Leave Event Handles and this handler contain the Validation code so that the Phone is validated when the use leaves the control.
When I hit Reset or Exit of the form, it not only clears the form, it also sends the focus back to the Phone field, causing the control (Textbox) to Validate.
I need the focus on the Phone control with at the validation on focus, is there a way I can prevent this behavior?
private void txtPhone_Leave(object sender, EventArgs e)
{
Int64 ConvertPhone;
if (txtPhone.Text.Trim().Length != 10)
{
lblPhoneError.Visible = true;
lblErrorIndicator.Visible = true;
lblErrorIndicator.Text = "*Valid 10 digit phone number required";
}
else if (Int64.TryParse(txtPhone.Text, out ConvertPhone))
{
lblPhoneError.Visible = false;
lblErrorIndicator.Visible = false;
txtPhone.MaxLength = 10;
txtPhone.Text = txtPhone.Text.Substring(0, 3) + "." + txtPhone.Text.Substring(3, 3) + "." + txtPhone.Text.Substring(6, 4);
}
}
private void btnClear_Click(object sender, EventArgs e)
{
txtPhone.Clear();
txtPhone.Focus();
}
private void txtPhone_Enter(object sender, EventArgs e)
{
txtPhone.Text = txtPhone.Text.Replace(".", "");
}
Thanks everyone!
if (txtPhone.Text.Trim().Length != 10)
{
if (txtPhone.Text != "")
{
lblErrorIndicator.Visible = true;
lblErrorIndicator.Text = "*Valid 10 digit phone number required";
}
}
private void btnClear_Click(object sender, EventArgs e)
{
txtPhone.Clear();
lblErrorIndicator.Text="";
txtPhone.Focus();
}
I can understand your problem but tell me what you want to do at the end?

Categories