I have a small mystery on my hands. I have created a form that prompts the user for some input then displays a CancelOK MessageBox showing the input. The user can enter the input either by clicking on a Submit button or by hitting the Enter key. The trick is, if the user cancels, I want the MessageBox to close and the original text in the text field to be highlighted again. Here is the code:
namespace WindowsFormsManualAdditions
{
public partial class ManualAdditionsForm : Form
{
public ManualAdditionsForm()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
additionsAction();
}
}
private void button1_Click(object sender, EventArgs e)
{
additionsAction();
}
private void additionsAction()
{
DialogResult btn = MessageBox.Show(textBox1.Text + " additions are being added manually", "Confirm Manual Additions", MessageBoxButtons.OKCancel);
if (btn == DialogResult.OK)
{
MessageBox.Show("Hellow World!");
this.Close();
}
else
{
textBox1.SelectionStart = 0;
textBox1.SelectionLength = textBox1.Text.Length;
}
}
}
}
The mystery is that when I run this form two different things can happen when the additionsAction() Method is called:
1) User enters data, hits Enter key, chooses cancel, message box disappears and original text is highlighted.
2) User enters data, clicks the Submit button, chooses cancel, message box disappears but the original text is NOT highlighted.
But both actions call the same method, namely additionsAction(), so how can the behaviour be different?!
Any advice is appreciated.
Regards.
The behavior is different because the action of clicking the mouse on the button removes focus from the textbox, whereas pressing a key does not.
Try adding a call to Control.Focus() or Control.Select() when the DialogResult is not OK:
textBox1.SelectionStart = 0;
textBox1.SelectionLength = textBox1.Text.Length;
textBox1.Focus();
// Or
textBox1.Select();
When Button1 is clicked, textBox1 doesn't have the focus, so no text is selected.
Related
This seems very basic but have not been able to find any information on it.
I have a button in a Windows form that is the AcceptButton and should always have the AcceptButton behavior i.e. pressing the enter key when focus is on the form should always click the button and it should always be highlighted to show that action is available.
However, when a different button is clicked, that button is now highlighted and when enter is pressed, that button is clicked instead of the AcceptButton.
Here is my test application that shows the behavior:
public Form1()
{
InitializeComponent();
AcceptButton = btnAccept;
}
private void btnAccept_Click(object sender, EventArgs e)
{
MessageBox.Show("You clicked the accept button");
Debug.WriteLine(AcceptButton == btnAccept ? "true" : "false");
}
private void btnNothing_Click(object sender, EventArgs e)
{
Debug.WriteLine(AcceptButton == btnAccept ? "true" : "false");
}
private void btnBrowse_Click(object sender, EventArgs e)
{
DialogResult result = folderBrowserDialog1.ShowDialog();
Debug.WriteLine(AcceptButton == btnAccept ? "true" : "false");
}
When the application launches initially - it works as I expect, btnAccept is highlighted and enter clicks that button.
However, when I click btnNothing or btnBrowse, that button is now highlighted and pressing enter clicks that button again. Additionally, the debug lines always show that btnAccept is still the AcceptButton even when the enter button is clicking a different button.
The CanFocus property that Button inherits from Control looks promising, but this property is read only.
What's going on here? Is there some property I can use to change this behavior?
Edit
Ended up going with this solution based on #AWinkle 's answer:
public Form1()
{
InitializeComponent();
AcceptButton = btnAccept;
}
private void btnAccept_Click(object sender, EventArgs e)
{
MessageBox.Show("You clicked the accept button");
}
private void btnNothing_Click(object sender, EventArgs e)
{
Button acceptButton = (Button)this.AcceptButton;
acceptButton.Select();
}
private void btnBrowse_Click(object sender, EventArgs e)
{
DialogResult result = folderBrowserDialog1.ShowDialog();
Button acceptButton = (Button)this.AcceptButton;
acceptButton.Select();
}
I used an if statement saying that if lblTotalAmount is populated then you can be able to click the second button. Because if lbltotalamount is populated then the first button was clicked to populate it. However, with my code below it works by showing the error message if you try to click the second button before the first button but then if i do it in the correct order it will not redirect me to the page i stated below. How can i correctly state this so that it will work?
protected void btnSubmitOrder_Click(object sender, EventArgs e)
{
if (lblTotalAmount == null)
{
Response.Redirect("~/Default.aspx");
}
else
{
lblMessage.Text = "Please click the Calculate Order Total button first";
}
}
You should be trying to validate on the Text property of the lablel instead
protected void btnSubmitOrder_Click(object sender, EventArgs e) {
if (string.IsNullOrEmpty(lblTotalAmount.Text))
{
Response.Redirect("~/Default.aspx");
}
else
{
lblMessage.Text = "Please click the Calculate Order Total button first";
}
}
I'm having a problem with making a button display the input in a textbox to a label. This is how it looks like.
Now forget about the radio buttons and the check boxes. I want what the user types inside the text box with the placeholder "Name:" to display to the label that's to the right of the button.
// Name TextBox
//***********************************************************
//Enter your name textbox
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
//Empties the textbox once it's focused
private void textBox1_Enter(object sender, EventArgs e)
{
if(textBox1.Focus())
textBox1.Text = String.Empty;
}
//Resets the placeholder text for password textbox
private void textBox1_Leave(object sender, EventArgs e)
{
if(!textBox1.Focused)
textBox1.Text = "Name: ";
}
//***********************************************************
// Password TextBox
//***********************************************************
//Enter your password textbox
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
//Empties the password textbox once it's focused
private void textBox2_Enter(object sender, EventArgs e)
{
if(textBox2.Focus())
textBox2.Text = String.Empty;
}
//Resets the placeholder text for password textbox
private void textBox2_Leave(object sender, EventArgs e)
{
if(!textBox2.Focused)
textBox2.Text = "Password: ";
}
//***********************************************************
//Display Name button
private void button1_Click(object sender, EventArgs e)
{
label5.Text = textBox1.Text;
}
//Display password button
private void button2_Click(object sender, EventArgs e)
{
label6.Text = textBox2.Text;
}
1) Just to clarify: I've made the initial text inside the text boxes a placeholder. And the placeholder text will reappear inside the text box once it loses focus. I've used both focus() method and focused property because I simply do not know the difference.
(I don't know if I should ask about the difference between the two in another question, so please let me know)
2) Now when I input whateva into the text box, then press the display button, the default placeholder text reappears and the input do not appear in the label. Naturally, I also don't want the placeholder text to ever appear at the label.
Obviously I'm new at Windows Forms and worse, I find it hard to articulate my questions when writing WinForms applications. So if any code is missing from my question, let me know.
You just need to change the check, if user has made any changes then you won't reappear the placeholder:
//Resets the placeholder text for password textbox
private void textBox2_Leave(object sender, EventArgs e)
{
if(!textBox2.Focused && textBox2.Text.Trim() == String.Empty)
textBox2.Text = "Password: ";
}
//Resets the placeholder text for password textbox
private void textBox1_Leave(object sender, EventArgs e)
{
if(!textBox1.Focused && textBox1.Text.Trim() == String.Empty)
textBox1.Text = "Name: ";
}
TextBox.Focus() is a method which make textbox an active control of the form. It also sets TextBox.Focused property to true.
This does look like a homework question, so I won't give you the answer, but I will help you out with some suggestions.
You need to stop being lazy with Control names. We all do it. But it has to stop. Six months from now you won't remember what label5 is.
I suggest you begin renaming the controls on your form. For example, change the Name textbox to nameTextBox, and change the Name button to nameButton, and change the Name label to nameLabel.
Breakpoints. Use them. When something doesn't work out as expected, set a breakpoint on the line where you are expecting something to happen. For example, if you write:
nameLabel.Text = nameTextBox.Text; then you should set a breakpoint on that line, Debug your app and step through, watching the output window for anything that doesn't look right.
i have this code to select all text in textbox if already have something wrote inside (TextLength > 0), it work perfect when i focus enter using tab on this textbox, then select all or not, little problem when focus in is made by mouse click, so i would like only to execute code bellow if focus enter isnt by mouse click, because if mouse click on textbox and it already have text, it will select all for about 0,1 seconds and unselect (but user can view blue select text than after unselect) and it isnt good
My code:
private void txtValormetrocubico_Enter(object sender, EventArgs e)
{
if (txtValormetrocubico.TextLength > 0)
{
txtValormetrocubico.SelectAll();
}
}
what i would like to do (incorrect syntax, only to understand my goal)
private void txtValormetrocubico_Enter(object sender, EventArgs e)
{
if (isnt mouse_click)
{
if (txtValormetrocubico.TextLength > 0)
{
txtValormetrocubico.SelectAll();
}
}
}
Thanks
In your Form's constructor you can hook the GotFocus event
public Form1()
{
textBox1.GotFocus += textBox1_GotFocus;
}
void textBox1_GotFocus(object sender, EventArgs e)
{
throw new NotImplementedException();
}
I have a winform form which has typical OK and Cancel buttons.
The OK button is set as the default button. When the user presses the ENTER key, the form is closed.
The form also has a text box which has a Search button beside it. The text box allows the user to enter search text and the Search button initiates the search function.
I would like the user to be able to press the ENTER key when the text box has the input focus and have the search function activate.
The problem is that the form is grabbing the ENTER key event before the text box's handler gets it.
EDIT: I've tried using the following event handlers, but they never get hit, and the form closes when the Enter key is hit:
private void txtFilter_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
Search();
e.Handled = true;
}
}
private void txtFilter_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
Search();
e.Handled = true;
}
}
I've also tried enabling the KeyPreview property on the form and implementing a KeyDown event handler for the form, but the Enter key never seems to cause any of these to be hit.
What is the best way to accomplish this?
Try handling the Enter and Leave events of the TextBox to clear out your form's AcceptButton property:
private void txtFilter_Enter(object sender, EventArgs e) {
this.AcceptButton = null;
}
private void txtFilter_Leave(object sender, EventArgs e) {
this.AcceptButton = closeButton;
}
Then you can just process your KeyUp event as your want:
private void txtFilter_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
Search();
}
}
Add a KeyDown event handler to the textBox and then add this to it
if (e.KeyCode == Keys.Enter)
{
btnSearch.PerformClick();
}