Make text box only highlight text on first click only - c#

Currently I have it so that when you select the text box it will highlight the text in it but what I want it to do is only do this for the first time that it is selected so that it will not delete the text that the user is typing each time. Here is what I am using to highlight the text:
private void txtName_Focus(object sender, EventArgs e)
{
bool isFirstTime = true;
if (isFirstTime == true){
txtName.SelectionStart = 0;
txtName.SelectionLength = txtName.Text.Length;
}
isFirstTime = false;
}

bool isFirstTime = true; this is your problem. It is being initialized to true every time the focus event is being called. Move bool isFirstTime; to be a member of your class and initialize it to true once in the declaration, constructor or the form load event

Maybe something like this:
bool txtNameWasFocused=false;
private void txtName_Focus(object sender, EventArgs e)
{
if(!txtNameWasFocused){
txtNameWasFocused=true;
txtName.SelectionStart = 0;
txtName.SelectionLength = txtName.Text.Length;
}
}
If you need this in many places, you might think of a derived text box with this special behaviour...

Related

Action perform button visible false does not work

Well, I have this situation, in a program I put a Button whose code is activated with PerformClick (programmatically), that button must be invisible in the interface so I put the value visible=false since the beginning of the program but the action on the event click doesn't perform, but if I put visible = true, the action actually is performed, any ideas of the problem?
private void dataGridView1_DoubleClick(object sender, EventArgs e)
{
if(_datosDe == "Insumos")
{
_btnRecargarInsumos.PerformClick();
}
this.Close();
}
_btnRecargarInsumos: is the button and is actually performed in another Form.
private void btnRecargarInsumos_Click(object sender, EventArgs e)
{
objGeneral.regresaDescripciones(ref dsDescripciones);
cbACDescripcion.DataSource = dsDescripciones.Tables[0];
cbACDescripcion.DisplayMember = "Nombre";
cbACDescripcion.ValueMember = "ID";
cbACDescripcion.SelectedIndex = -1;
cbACDescripcion.Text = "";
}
cbACDescripcion: Combobox which will be "reloaded" with the values of the DataSet: dsDescripciones.
The property visible is false since the beginnig of the program, but I also try to set visible=true and just before the method PerformClick() change it, but is the same.
But if I put visible=true since the beginning it works in that way.
If you click a button that's not visible or not enabled, nothing happens, even if you click it programmatically. Here's a workaround that works for me, although it's a bit of a hack:
_btnRecargarInsumos.SuspendLayout();
_btnRecargarInsumos.Visible = true;
_btnRecargarInsumos.PerformClick();
_btnRecargarInsumos.Visible = false;
_btnRecargarInsumos.ResumeLayout();
Why not just put your code in a separate method?
Example:
private StuffToDoAtClick()
{
objGeneral.regresaDescripciones(ref dsDescripciones);
cbACDescripcion.DataSource = dsDescripciones.Tables[0];
cbACDescripcion.DisplayMember = "Nombre";
cbACDescripcion.ValueMember = "ID";
cbACDescripcion.SelectedIndex = -1;
cbACDescripcion.Text = "";
}
//Your Button.Click() code//
private void btnRecargarInsumos_Click(object sender, EventArgs e)
{
StuffToDoAtClick()
}
//Your Datagridview code//
private void dataGridView1_DoubleClick(object sender, EventArgs e)
{
if(_datosDe == "Insumos")
{
StuffToDoAtClick();
}
this.Close();
}

Disable button when text is entered in text box correctly and adding dialog box in c#

I have been trying to figure out on disabling the text box when text is entered in the text box. I am able to do this but I have also got another problem which is, lets say you have a text box with some word i.e "Welcome". If I edit that and add more letter on to that i.e "WelcomeSSS" adding SSS then text is enabled. But when I delete "SSS" from that text box, button is still enabled and not DISABLED as the text is the same as it was before editing.
How do I make sure that the text is disabled in this situation?
And also I want to add dialog box when a user click on different button to go to different page without saving the edited content. How do i do this?
Here is my code so far:
private void textbox1_IsChanged(object sender, KeyEventArgs e)
{
//SaveButton.IsEnabled = !string.IsNullOrEmpty(TextBox1.Text);
if (TextBox1.Text.Trim().Length > 0)
{
SaveButton.IsEnabled = true;
}
if (WpfHelpers.Confirmation(resources.QuitWithoutSaving, resources.Changes))
{
}
}
This is using KeyUp event handler in wpf.
If I understood your question correctly...
private void textbox1_IsChanged(object sender, KeyEventArgs e)
{
if (textbox1.Text == "Welcome"){
SaveButton.IsEnabled = false;
}
else{
SaveButton.IsEnabled = true;
}
}
You need a data structure for storing the saved values. E.g. a List of strings. In the following snippet, these values are stored in the SavedTextBoxTexts list.
At first, the SaveButton gets disabled (you can do this in the XAML as well). When SaveButton has been clicked, the textBox1.text value will be stored in the list and the button gets disabled.
When textBox1.text is edited and SaveButton exists (already), the different conditions get checked.
If textBox1.text is already stored in SavedTextBoxTexts or textBox1.text is empty or contains only whitespace characters, SaveButton gets disabled. Otherwise the SaveButton will be enabled.
public partial class MainWindow : Window
{
private List<string> SavedTextBoxTexts = new List<string>();
public MainWindow()
{
InitializeComponent();
// Disable button right from the beginning.
SaveButton.IsEnabled = false;
}
private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
// The function may be called, while the window has not been created completely.
// So we have to check, if the button can already be referenced.
if (SaveButton != null)
{
// Check if textBox1 is empty or
// textBox1.text is already in the list of saved strings.
if (String.IsNullOrEmpty(textBox1.Text) ||
textBox1.Text.Trim().Length == 0 ||
SavedTextBoxTexts.IndexOf(textBox1.Text.Trim()) >= 0)
{
// Disable Button
SaveButton.IsEnabled = false;
}
else
{
// If textBox1.text has not been saved already
// or is an empty string or a string of whitespaces,
// enable the SaveButton (again).
SaveButton.IsEnabled = true;
}
}
}
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
// Store the text in textBox1 into the SavedTextBoxTexts list.
SavedTextBoxTexts.Add(textBox1.Text.Trim());
// Disable the SaveButton.
SaveButton.IsEnabled = false;
}
// This is executed, when the other button has been clicked.
// The text in textBox1 will not be saved.
private void AnotherButton_Click(object sender, RoutedEventArgs e)
{
if (WpfHelpers.Confirmation(resources.QuitWithoutSaving, resources.Changes))
{
// Move to other page ...
}
}
}

messagebox always pop up when clicking combo box

Good day, anyone can help me with this problem... I have a combo box and a textbox. the textbox(txtFruitNo) will check the length of text under Leave event. It is ok. But if I click on the combo box while txtFruitNo is not yet completed. It needs me to complete first the length of txtFruitNo then only I can click the combo box.
I do not want to show the messagebox if I click on the combo box even if the length of the txtFruitNo is not yet completed.
Thanks
private void cmbFruitSelection_SelectedIndexChanged(object sender, EventArgs e)
{
DateTime thetime = DateTime.Now;
String varApple = "App-Red";
String varBanana = "Ban-Yellow";
if (cmbFruitSelection.SelectedItem.ToString() == "Apple")
{
txtFruitNo.Text = varApple.ToString() + thetime.ToString("yyyy");
txtFruitNo.SelectionStart = txtFruitNo.Text.Length;
txtFruitNo.MaxLength = 18;
}
else if (cmbFruitSelection.SelectedItem.ToString() == "Banana")
{
txtFruitNo.Text = varBanana.ToString() + thetime.ToString("yyyy");
txtFruitNo.SelectionStart = txtFruitNo.Text.Length;
txtFruitNo.MaxLength = 17;
}
}
private void txtFruitNo_Leave(object sender, EventArgs e)
{
if (txtFruitNo.TextLength != txtFruitNo.MaxLength)
{
MessageBox.Show("Your fruit number is too short. Please check.");
txtFruitNo.Focus();
}
else
{
// Do something here
}
}
At what point is it important for continuation of the program that the "Fruit Number" is within parameters. If it is not at the time of leaving focus try moving it to a different control for example the "OK" button could run the parameter check and if valid continue if not flag mesage box and return to the textbox
Since your requirement is to only to do the validation and prompt the message box once the user has selected a value from the combo, please do the following;
Introduce a form variable
private bool isComboClicked = false;
Add the below line to cmbFruitSelection_SelectedIndexChanged
isComboClicked = true;
Adding the above line at the beginning of the above event would prompt the length validation message on selection of value from the combo. If you want to prompt message for specific value on the combo move it within the if statements if (comboBox1.SelectedItem.ToString() == "Apple") etc.
Now in txtFruitNo_Leave event enclose the code within the below if condition.
if (isComboClicked)
{
// Your Code
if (txtFruitNo.TextLength != txtFruitNo.MaxLength)
{
MessageBox.Show("Your fruit number is too short. Please check.");
txtFruitNo.Focus();
}
else
{
// Do something here
}
}
As I understand:
You have "validation" on TextBox in Leave eventhandler, which show error message if validation fails.
But if TextBox.Leave event was raised by selecting ComboBox control, then validation must be suppressed.
Create Panel and put there only txtFruitNo and cmbFruitSelection controls.
// Validation function
private bool IsTextBoxValid()
{
return this.txtFruitNo.Length == this.txtFruitNo.maxlength;
}
Then create and hook up Validating eventhandler for Panel where you will validate txtFruitNo
private void Panel_Validating(Object sender, CancelEventArgs e)
{
if(this.IsTextBoxValid() == false)
{
e.Cancel = true;
MessageBox.Show("Your fruit number is too short. Please check.") ;
}
}
Validating will be raised only when focus move outside of the panel.
Using Validating event will prevent changing focus to outside controls automatically if e.Cancel = true
In that case combobox cmbFruitSelection can be focused and user can complete txtFruitNo text by selecting valid value from ComboBox.
I think using of ErrorProvider control will be more friendly for the user, then MessageBox.
Add ErrorProvider control in the Form through designer and add few lines in the code
private void Panel_Validating(Object sender, CancelEventArgs e)
{
if(this.IsTextBoxValid() == false)
{
e.Cancel = true;
this.ErrorProvider1.SetError(txtFruitNo,
"Your fruit number is too short. Please check.");
}
else
{
this.ErrorProvider1.Clear();
}
}
And clear error after valid value was used from ComboBox
private void cmbFruitSelection_SelectedIndexChanged(object sender, EventArgs e)
{
DateTime thetime = DateTime.Now;
String varApple = "App-Red";
String varBanana = "Ban-Yellow";
if (cmbFruitSelection.SelectedItem.ToString() == "Apple")
{
txtFruitNo.Text = varApple.ToString() + thetime.ToString("yyyy");
txtFruitNo.SelectionStart = txtFruitNo.Text.Length;
txtFruitNo.MaxLength = 18;
//Clear error
this.ErrorProvider1.Clear();
}
else if (cmbFruitSelection.SelectedItem.ToString() == "Banana")
{
txtFruitNo.Text = varBanana.ToString() + thetime.ToString("yyyy");
txtFruitNo.SelectionStart = txtFruitNo.Text.Length;
txtFruitNo.MaxLength = 17;
//Clear error
this.ErrorProvider1.Clear();
}
}

Enabling a button after number of edittexts has been filled

I want to make an activity with few edittext fields and a button which should be disabled until the most important of these fields has been filled. This is the code I am using but the button is staying disabled the whole time:
doneButton implementation
if((isEmpty(inputType)) || (isEmpty(inputAmount)) || (isEmpty(inputSupplier)))
doneButton.Enabled = false;
else
doneButton.Enabled = true;
This is the code for the isEmpty() method, which is checking if the edittext is empty or not:
private Boolean isEmpty(EditText etText) {
return etText.Text.ToString().Length == 0;
}
Thanks in advance ! :)
Why not use the TextChanged event:
EditText input = FindViewById<EditText>(Resource.Id.editText1);
input.TextChanged += input_TextChanged;
and then define the event handler for it?
private void input_TextChanged(object sender, TextChangedEventArgs e)
{
Console.WriteLine("input text changed");
// if text bigger than 0, enable the button, otherwise disable it
}
Much cleaner IMHO.
You will need to add this implementation(your code to check if the button stays disabled) inside the TextWatcher#afterTextChanged method , which you would add as a TextChanged listener. You will need to do this for all the edit texts you think are important.
Something like this:
inputType.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
if((isEmpty(inputType)) || (isEmpty(inputAmount)) || (isEmpty(inputSupplier)))
doneButton.setEnabled(false);
else
doneButton.setEnabled(true);
}
});
Similar listeners over inputAmount and inputSupplier should do the task.
The question is: On which event did you attach this code?
You can, for example, create a TextWatcher object and attach it to the relevant text fields. Something like:
inputType.addTextChangedListener(watcher);
In this watcher you would do the checks you have written and do:
doneButton.setEnabled(true/false);
I solved it like this:
inputType.AfterTextChanged += new EventHandler<AfterTextChangedEventArgs> (OnTextChange);
inputAmount.AfterTextChanged += new EventHandler<AfterTextChangedEventArgs> (OnTextChange);
inputSupplier.AfterTextChanged += new EventHandler<AfterTextChangedEventArgs> (OnTextChange);
where the OnTextChange() method is this:
public void OnTextChange(object sender, EventArgs e)
{
if((isEmpty(inputType)) || (isEmpty(inputAmount)) || (isEmpty(inputSupplier)))
doneButton.Enabled = false;
else
doneButton.Enabled = true;
}

Making TextBox Clear when user starts typing

I have two text boxes in a win forms that the user will be typing information into. I would like to clear the text box when the user start typing. I am using the TextChanged event handler, so every time I type it will erase, which makes me not able to type anything into the text box. Here is the code I am using:
private void TXTBX_HourlyRatae_TextChanged(object sender, EventArgs e)
{
TXTBX.HourlyRate.Clear();
TXTBX.HoursWorked.Clear();
}
I understand that everytime I type into the text box I will be executing this event handler, but I don't know how to go about making it execute only the first time I type into the text box.
private bool firsttime = true;
private void TXTBX_HourlyRatae_TextChanged(object sender, EventArgs e)
{
if (firsttime)
{
TXTBX.HourlyRate.Clear();
TXTBX.HoursWorked.Clear();
firsttime = false;
}
}
if you want to do it everytime you enter the textbox handle the loss focus event
private void TXTBX_HourlyRatae_LostFocus(object sender, System.EventArgs e)
{
} firsttime = true;
Move your Clear() calls into the corresponding Enter or GotFocus events.
Create a new private class member:
private bool _userHasEnteredText = false;
Only erase the text when this bool is false, then set this bool to true once you've cleared the text the first time.

Categories

Resources