How can I make button property set to enabled=true after all my textboxes are not empty?
I'm learning programming and my apps are simple.
I know how to enable this property when one of my textboxes have text but this is not the case.
Use case is that user need to put data in both textboxes and after that will be able to click btn.
How in most simple way can I validate all form and then enable button?
There are just 2 tb:
https://i.imgur.com/JUslNWE.png
You need to create a TextBox_TextChanged event and subscribe to all text boxes.
private void TextBox_TextChanged(object sender, EventArgs e)
{
int notEmptyTextBoxCount = 0;
int textBoxCount = 0;
foreach (var item in Controls)
{
if (item is TextBox txtb)
{
textBoxCount++;
if (txtb.Text != String.Empty)
notEmptyTextBoxCount++;
}
}
if (textBoxCount == notEmptyTextBoxCount)
button.Enabled = true;
else
button.Enabled = false;
}
Thanks guys for all feedback.
I have managed to do this this way:
private void ValidateTextBoxes()
{
if (loginTextBox.Text.Length != 0 && passTextBox.Text.Length != 0)
{
generateHashBtn.Enabled = true;
}
else
{
generateHashBtn.Enabled = false;
}
}
private void TextBox1_TextChanged(object sender, EventArgs e)
{
ValidateTextBoxes();
}
private void TextBox2_TextChanged(object sender, EventArgs e)
{
ValidateTextBoxes();
}
I'm trying select an item from list box when is right clicked and show the ContextMenuStrip to display my options available, but when I click everywhere in the control (list box) is showing the ContextMenuStrip.
This is what I have in code:
private void lbSMTPEmails_MouseDown(object sender, MouseEventArgs e)
{
int SelectedIndex = lbSMTPEmails.IndexFromPoint(e.X, e.Y);
if (SelectedIndex == -1)
lbSMTPEmails.ContextMenuStrip.Hide();
else
{
lbSMTPEmails.SelectedIndex = SelectedIndex;
lbSMTPEmails.ContextMenuStrip.Show();
}
}
do you have any idea how to solve this?
Use opening event of ContextMenuStrip
void cms_Opening(object sender, System.ComponentModel.CancelEventArgs e)
{
int SelectedIndex = lbSMTPEmails.IndexFromPoint( lbSMTPEmails.PointToClient(Cursor.Position) );
if (SelectedIndex == -1)
e.Cancel = true;
else
{
lbSMTPEmails.SelectedIndex = SelectedIndex;
}
}
I did by this way and it worked!
private void listbox_MouseDown(object sender, MouseEventArgs e)
{
ShowMenuStrip = listbox.IndexFromPoint(e.Location) >= 0; //This is a global bool variable
if (ShowMenuStrip)
listbox.SelectedIndex = listbox.IndexFromPoint(e.Location);
else
listbox.SelectedIndex = -1;
}
private void ContextMenuStrip_Opening(object sender, CancelEventArgs e)
{
e.Cancel = !ShowMenuStrip;
}
I've a project where I need to focus previous field if current one is empty but user keep deleting. Like when you type CD-Key somewhere. You have couple blocks with 4-5 symbols each. And if you erase 3rd textBox for example you will be forced back to the second textBox right after 3rd one become emprty.
if (textBox2.Text.Length == 0)
{
Keyboard.Focus(textBox1);
}
This code works fine but considering that I've another onfocus event so textBox2 become empty as soon as got focus and due to code above focus forcing back to the textBox1. So it's looped.
If I get it right I need to catch pressing the Delete button, right? But here is my problem goes. I don't know how to insert this code
private void Window_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Delete)
{
if (textBox2.Text.Length == 0)
{
Keyboard.Focus(textBox1);
}
}
}
inside this function:
private void textBox2_TextChanged(object sender, TextChangedEventArgs e)
{
if (textBox2.Text.Length == 2)
{
Keyboard.Focus(textBox3);
}
// HERE I NEED SOMETHING LIKE ELSE IF (e.Key == Key.Delete) {...
}
Help me please.
UPD. I've tried one more solution but it doesn't work:
private void textBox2_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Delete)
{
if (textBox2.Text.Length == 0)
{
Keyboard.Focus(textBox1);
}
}
}
Here is the generic soution for arbitrary amount of TextBox'es.
The initialization of the TextBox'es list:
private readonly List<TextBox> _textBoxes;
public MainWindow()
{
InitializeComponent();
_textBoxes = new List<TextBox> { _textBox1, _textBox2, _textBox3 };
}
The version with KeyUp event:
private void TextBox_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Tab)
return;
var current = (TextBox)sender;
if (current.Text.Any())
return;
var index = _textBoxes.IndexOf(current);
if (index == 0)
return;
var previous = _textBoxes[index - 1];
previous.Focus();
previous.CaretIndex = previous.Text.Length;
}
The above version dissalows to jump through TextBox'es in press and hold scenario. To get around this, use TextChanged event:
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
var current = (TextBox)sender;
if (current.Text.Any())
return;
var index = _textBoxes.IndexOf(current);
if (index == 0)
return;
var previous = _textBoxes[index - 1];
previous.Focus();
previous.CaretIndex = previous.Text.Length;
}
Third solution with PreviewKeyDown that supports only Key.Delete:
private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key != Key.Delete)
return;
var current = (TextBox)sender;
if (current.Text.Length != 0)
return;
var index = _textBoxes.IndexOf(current);
if (index == 0)
return;
var previous = _textBoxes[index - 1];
previous.Focus();
previous.CaretIndex = 0;
}
Fourth solution also with PreviewKeyDown that supports both Key.Delete and Key.Back:
private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key != Key.Delete && e.Key != Key.Back)
return;
var current = (TextBox)sender;
if (current.Text.Length != 0)
return;
var index = _textBoxes.IndexOf(current);
if (index == 0)
return;
var previous = _textBoxes[index - 1];
previous.Focus();
if (e.Key == Key.Delete)
previous.CaretIndex = 0;
}
Finally. This one works:
private void textBox2_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Delete)
{
if (textBox2.Text.Length == 0)
{
Keyboard.Focus(textBox1);
}
}
}
This is not tested but should also work.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox2_KeyDown(object sender, KeyEventArgs e)
{
if (textBox2.Text == "")
{
textBox1.Focus();
}
}
private void textBox3_KeyDown(object sender, KeyEventArgs e)
{
if (textBox3.Text == "")
{
textBox2.Focus();
}
}
}
I have a DataGridView, with several ComboBoxColumns in it. Is there a way to create an event, so that each time a ComboBoxColumncell is entered and an item selected, the event fires?
All I can figure out so far is this:
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0)
{
MessageBox.Show("Amanda");
}
}
Which is not doing anything.
You're probably looking for the EditingControlShowing event.
See here for a similar question:
"SelectedIndexChanged" event in ComboBoxColumn on Datagridview
try this one.
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
ComboBox nameComboBox = e.Control as ComboBox;
if (dataGridView1.CurrentCell.ColumnIndex == 0)
{
if (nameComboBox != null)
{
((ComboBox)e.Control).DropDownStyle = ComboBoxStyle.DropDown;
((ComboBox)e.Control).AutoCompleteSource = AutoCompleteSource.ListItems;
((ComboBox)e.Control).AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest;
nameComboBox .SelectedIndexChanged -= (nameComboBox _SelectedIndexChanged);
nameComboBox .SelectedIndexChanged += (nameComboBox _SelectedIndexChanged);
}
}
}
private void nameComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex == 1)
{
var rowindex = dataGridView1.CurrentCell.RowIndex;
if (dataGridView1[1, rowindex].EditedFormattedValue != null)
{
Consol.WriteLine(dataGridView1[1, rowindex].EditedFormattedValue.ToString());
}
else
{
//No value in cell
}
}
}
How do you auto highlight text in a textbox control when the control gains focus.
In Windows Forms and WPF:
textbox.SelectionStart = 0;
textbox.SelectionLength = textbox.Text.Length;
If you want to do it for your whole WPF application you can do the following:
- In the file App.xaml.cs
protected override void OnStartup(StartupEventArgs e)
{
//works for tab into textbox
EventManager.RegisterClassHandler(typeof(TextBox),
TextBox.GotFocusEvent,
new RoutedEventHandler(TextBox_GotFocus));
//works for click textbox
EventManager.RegisterClassHandler(typeof(Window),
Window.GotMouseCaptureEvent,
new RoutedEventHandler(Window_MouseCapture));
base.OnStartup(e);
}
private void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
(sender as TextBox).SelectAll();
}
private void Window_MouseCapture(object sender, RoutedEventArgs e)
{
var textBox = e.OriginalSource as TextBox;
if (textBox != null)
textBox.SelectAll();
}
In ASP.NET:
textbox.Attributes.Add("onfocus","this.select();");
It is very easy to achieve with built in method SelectAll
Simply cou can write this:
txtTextBox.Focus();
txtTextBox.SelectAll();
And everything in textBox will be selected :)
If your intention is to get the text in the textbox highlighted on a mouse click you can make it simple by adding:
this.textBox1.Click += new System.EventHandler(textBox1_Click);
in:
partial class Form1
{
private void InitializeComponent()
{
}
}
where textBox1 is the name of the relevant textbox located in Form1
And then create the method definition:
void textBox1_Click(object sender, System.EventArgs e)
{
textBox1.SelectAll();
}
in:
public partial class Form1 : Form
{
}
I think the easiest way is using TextBox.SelectAll like in an Enter event:
private void TextBox_Enter(object sender, EventArgs e)
{
((TextBox)sender).SelectAll();
}
Here's the code I've been using. It requires adding the attached property to each textbox you wish to auto select. Seeing as I don't want every textbox in my application to do this, this was the best solution to me.
public class AutoSelectAll
{
public static bool GetIsEnabled(DependencyObject obj)
{
return (bool)obj.GetValue(IsEnabledProperty);
}
public static void SetIsEnabled(DependencyObject obj, bool value)
{
obj.SetValue(IsEnabledProperty, value);
}
static void ue_Loaded(object sender, RoutedEventArgs e)
{
var ue = sender as FrameworkElement;
if (ue == null)
return;
ue.GotFocus += ue_GotFocus;
ue.GotMouseCapture += ue_GotMouseCapture;
}
private static void ue_Unloaded(object sender, RoutedEventArgs e)
{
var ue = sender as FrameworkElement;
if (ue == null)
return;
//ue.Unloaded -= ue_Unloaded;
ue.GotFocus -= ue_GotFocus;
ue.GotMouseCapture -= ue_GotMouseCapture;
}
static void ue_GotFocus(object sender, RoutedEventArgs e)
{
if (sender is TextBox)
{
(sender as TextBox).SelectAll();
}
e.Handled = true;
}
static void ue_GotMouseCapture(object sender, MouseEventArgs e)
{
if (sender is TextBox)
{
(sender as TextBox).SelectAll();
}
e.Handled = true;
}
public static readonly DependencyProperty IsEnabledProperty = DependencyProperty.RegisterAttached("IsEnabled", typeof(bool),
typeof(AutoSelectAll), new UIPropertyMetadata(false, IsEnabledChanged));
static void IsEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var ue = d as FrameworkElement;
if (ue == null)
return;
if ((bool)e.NewValue)
{
ue.Unloaded += ue_Unloaded;
ue.Loaded += ue_Loaded;
}
}
}
The main change I made here was adding a loaded event to many of the examples I've seen. This allows the code to continue working after it's unloaded (ie. a tab is changed). Also I included code to make sure the text gets selected if you click on the textbox with the mouse, and not just keyboard focus it. Note: If you actually click on the text in the textbox, the cursor is inserted between the letters as it should.
You can use this by including the following tag in your xaml.
<TextBox
Text="{Binding Property}"
Library:AutoSelectAll.IsEnabled="True" />
If you need to do this for a large number of textboxes (in Silverlight or WPF), then you can use the technique used in the blog post: http://dnchannel.blogspot.com/2010/01/silverlight-3-auto-select-text-in.html. It uses Attached Properties and Routed Events.
You can use this, pithy. :D
TextBox1.Focus();
TextBox1.Select(0, TextBox1.Text.Length);
If you wanted to only select all the text when the user first clicks in the box, and then let them click in the middle of the text if they want, this is the code I ended up using.
Just handling the FocusEnter event doesn't work, because the Click event comes afterwards, and overrides the selection if you SelectAll() in the Focus event.
private bool isFirstTimeEntering;
private void textBox_Enter(object sender, EventArgs e)
{
isFirstTimeEntering = true;
}
private void textBox_Click(object sender, EventArgs e)
{
switch (isFirstTimeEntering)
{
case true:
isFirstTimeEntering = false;
break;
case false:
return;
}
textBox.SelectAll();
textBox.SelectionStart = 0;
textBox.SelectionLength = textBox.Text.Length;
}
if you want to select all on "On_Enter Event" this won't Help you achieving your goal.
Try using "On_Click Event"
private void textBox_Click(object sender, EventArgs e)
{
textBox.Focus();
textBox.SelectAll();
}
On events "Enter" (for example: press Tab key) or "First Click" all text will be selected. dotNET 4.0
public static class TbHelper
{
// Method for use
public static void SelectAllTextOnEnter(TextBox Tb)
{
Tb.Enter += new EventHandler(Tb_Enter);
Tb.Click += new EventHandler(Tb_Click);
}
private static TextBox LastTb;
private static void Tb_Enter(object sender, EventArgs e)
{
var Tb = (TextBox)sender;
Tb.SelectAll();
LastTb = Tb;
}
private static void Tb_Click(object sender, EventArgs e)
{
var Tb = (TextBox)sender;
if (LastTb == Tb)
{
Tb.SelectAll();
LastTb = null;
}
}
}
I don't know why nobody mentioned that but you can also do this, it works for me
textbox.Select(0, textbox.Text.Length)
textBoxX1.Focus();
this.ActiveControl = textBoxX1;
textBoxX1.SelectAll();
In window form c#. If you use Enter event it will not work. try to use MouseUp event
bool FlagEntered;
private void textBox1_MouseUp(object sender, MouseEventArgs e)
{
if ((sender as TextBox).SelectedText == "" && !FlagEntered)
{
(sender as TextBox).SelectAll();
FlagEntered = true;
}
}
private void textBox1_Leave(object sender, EventArgs e)
{
FlagEntered = false;
}
textbox.Focus();
textbox.SelectionStart = 0;
textbox.SelectionLength = textbox.Text.Length;