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 = "+";
}
}
Related
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...
I need to double click the Masked Textbox which is inside datagridview.
But when i try to enter some value after the masked textbox gets focus, I am not able to enter any value. But I can able to enter a value when i double click using mouse. So i checked by writing SendKeys.Send("{F2}") in DataGridView.KeyPress event which works for all the normal columns to edit(like textbox), but not able to enter a value in MaskedTextBox.
Please assist me on the SendKeys.Send() for mouse double click.
In the DataGridView, key press event tried to call sendKeys.send("{F2}").
sendKeys.send("{F2}")
When the Masked textbox inside datagridview comes to focus, user should be able to enter a value.
Below is my sample coding :
private void Form7_Load(object sender, EventArgs e)
{
DataGridViewComboBoxColumn TpyeCol = new DataGridViewComboBoxColumn();
TpyeCol.Name = "Type";
TpyeCol.HeaderText = "Type";
TpyeCol.Items.AddRange(new string[] { "Home Phone", "Cell", "Work", "Email" });
this.dataGridView1.Columns.Add(TpyeCol);
this.dataGridView1.Columns.Add("Description", "Description");
this.dataGridView1.Rows.Add("Home Phone","");
this.maskedTextBox = new MaskedTextBox();
this.maskedTextBox.Visible = false;
this.dataGridView1.Controls.Add(this.maskedTextBox);
this.dataGridView1.CellBeginEdit += new DataGridViewCellCancelEventHandler(dataGridView1_CellBeginEdit);
this.dataGridView1.CellEndEdit += new DataGridViewCellEventHandler(dataGridView1_CellEndEdit);
this.dataGridView1.Scroll += new ScrollEventHandler(dataGridView1_Scroll);
}
void dataGridView1_Scroll(object sender, ScrollEventArgs e)
{
if (this.maskedTextBox.Visible)
{
Rectangle rect = this.dataGridView1.GetCellDisplayRectangle( this.dataGridView1.CurrentCell.ColumnIndex, this.dataGridView1.CurrentCell.RowIndex, true);
this.maskedTextBox.Location = rect.Location;
}
}
void dataGridView1_CellBeginEdit(object sender,DataGridViewCellCancelEventArgs e)
{
if (e.ColumnIndex == this.dataGridView1.Columns["Description"].Index &&
e.RowIndex < this.dataGridView1.NewRowIndex)
{
string type = this.dataGridView1["Type",e.RowIndex].Value.ToString();
if (type == "Home Phone" || type == "Cell" || type == "Work")
{
this.maskedTextBox.Mask = "00/00/0000";
Rectangle rect = this.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex,e.RowIndex,true);
this.maskedTextBox.Location = rect.Location;
this.maskedTextBox.Size = rect.Size;
this.maskedTextBox.Text = "04/02/2019";
if (this.dataGridView1[e.ColumnIndex, e.RowIndex].Value != null)
{
this.maskedTextBox.Text = this.dataGridView1[e.ColumnIndex,
e.RowIndex].Value.ToString();
}
this.maskedTextBox.Visible = true;
}
}
}
void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (this.maskedTextBox.Visible)
{
this.dataGridView1.CurrentCell.Value = this.maskedTextBox.Text;
this.maskedTextBox.Visible = false;
}
}
void dataGridView1_KeyPress(object sender, DataGridKeyPressEventArgs e)
{
If(dataGridView1.ColumnIndex = 1)
{
SendKeys.Send("{F2}") //To Point cursor in position 1 of Masked TextBox but not able to edit the masked textbox in DGV
}
}
MaskedTextBox maskedTextBox;
I have a simple keypad with 0-9, a Clear button, and an Enter Button. Clicking the numbers places the content into a PasswordBox. Clicking the Clear button simulates a backspace, and the Enter Button acts as a submit for predefined 4 digit codes. If the correct code is entered, it appends to a textbox showing that access was granted, else, access denied.
I am having no problems except when trying to set a MaxLength on the PasswordBox. I have tried it in my XAML with:
<PasswordBox PasswordChanged="securityCodeTextBox_PasswordChanged" MaxLength="4" KeyDown="securityCodeTextBox_KeyDown" x:Name="securityCodeTextBox" PasswordChar="•" HorizontalAlignment="Left" Margin="117,20,0,0" VerticalAlignment="Top" Height="23" Width="213"/>
I've also tried it programmatically with:
securityCodeTextBox.MaxLength = 4;
This is the only code in my function for the numeric buttons:
private void ButtonClickNum(object sender, RoutedEventArgs e)
{
Button button = (Button)sender;
securityCodeTextBox.Password += button.Content.ToString();
}
I don't have to implement this, since if the code is wrong, it will just log "Access Denied" in the textbox below it. However, I am really curious on how to do this after realizing the MaxLength is for keyboard input, not button clicks. I currently have the keyboard completely disabled with:
//Prevent keyboard input
private void securityCodeTextBox_KeyDown(object sender, KeyEventArgs e)
{
e.Handled = true;
}
Next attempt
I created a very sloppy way to disable all but the Clear and Enter buttons if the length reaches >=4 with these code snippets in the Num and Clear Button Click functions:
private void ButtonClickNum(object sender, RoutedEventArgs e)
{
Button button = (Button)sender;
securityCodeTextBox.Password += button.Content.ToString();
//Disable all buttons if MaxLength is reached
if(securityCodeTextBox.Password.Length >= 4)
{
button0.IsEnabled = false;
button1.IsEnabled = false;
button2.IsEnabled = false;
button3.IsEnabled = false;
button4.IsEnabled = false;
button5.IsEnabled = false;
button6.IsEnabled = false;
button7.IsEnabled = false;
button8.IsEnabled = false;
button9.IsEnabled = false;
}
}
Clear Button
/**
* Remove(int startIndex, int count) startIndex = position, count = num of chars to delete
*/
private void ButtonClickClear(object sender, RoutedEventArgs e)
{
if (securityCodeTextBox.Password.Length > 0)
{
securityCodeTextBox.Password = securityCodeTextBox.Password.Remove(securityCodeTextBox.Password.Length - 1, 1);
}
//Enable all the buttons again once password is less than MaxLength
if (securityCodeTextBox.Password.Length < 4)
{
button0.IsEnabled = true;
button1.IsEnabled = true;
button2.IsEnabled = true;
button3.IsEnabled = true;
button4.IsEnabled = true;
button5.IsEnabled = true;
button6.IsEnabled = true;
button7.IsEnabled = true;
button8.IsEnabled = true;
button9.IsEnabled = true;
}
}
Is there a cleaner way to implement the MaxLength method when the input is the content of a button?
I never worked with WPF or password input Controls before, but I would try it like this, it just wont add up the password if the length is reached.
private void ButtonClickNum(object sender, RoutedEventArgs e)
{
Button button = (Button)sender;
if(securityCodeTextBox.Password.Length < 4)
securityCodeTextBox.Password += button.Content.ToString();
}
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;
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?