Apply event format to all textboxes - c#

I have written this code:
private void maskedNASC_KeyDown(object sender, KeyEventArgs e)
{
maskedNASC.BackColor = Color.Aqua;
}
private void maskedNASC_Leave(object sender, EventArgs e)
{
maskedNASC.BackColor = Color.White;
}
I want to apply this property to all the textboxes and masked texts of the form.
I have see many codes like this:
void SetProperty(Control ctr) // resalta textbox onfocus
{
foreach (Control control in ctr.Controls)
{
if (control is TextBox)
{
control.Leave == control.BackColor = Color.Aqua;
control.KeyDown += BackColor = Color.White ;
}
}
}
What is the right way to write this??
Thanks. Alejandro.
I have add this to the form1.designer :
this.maskedNASC.Leave += TextBoxEvent_Leave;
this.maskedNASC.KeyDown += TextBox_KeyDown;
but the code below have an error
[![enter image description here][1]][1]

You can write that in this way
void SetProperty(Control ctr) // resalta textbox onfocus
{
foreach (Control control in ctr.Controls)
{
if (control is TextBox)
{
control.Leave -= control_Leave; //Remove control_Leave if already binded.
control.Leave += control_Leave; //Assigne control_Leave
control.KeyDown -= control_KeyDown ; //Remove control_KeyDown if already binded.
control.KeyDown += control_KeyDown ; //Assigne control_KeyDown
}
}
}
private void control_Leave(object sender, EventArgs e)
{
((Control)sender).BackColor = Color.Aqua;
}
private void control_KeyDown(object sender, KeyEventArgs e)
{
((Control)sender).BackColor = Color.White;
}

You can make the event more general for example (using pattern matching in C# 8.0)
private void TextBoxEvent_Leave(object sender, EventArgs e)
{
if (sender is TextBox bx)
{
bx.BackColor = Color.White;
}
}
private void TextBox_KeyDown(object sender, EventArgs e)
{
if (sender is TextBox bx)
{
bx.BackColor = Color.Red;
}
}
and in the constructor just add
this.maskedNASC.Leave += TextBoxEvent_Leave;
this.maskedNASC.KeyDown += TextBox_KeyDown;
for each text box you have
you can also try the following depending on the C# version you are using
private void TextBoxEvent_Leave(object sender, EventArgs e)
{
if (sender is TextBox)
{
((TextBox)sender).BackColor = Color.White;
}
}
private void TextBox_KeyDown(object sender, EventArgs e)
{
if (sender is TextBox)
{
((TextBox)sender).BackColor = Color.Red;
}
}

Related

Multiple Textbox if Condition ( if a certain value is Greater than certain value do this ) [duplicate]

Hello I was wondering how can I keep an eye on all textboxes in Form whether in any of them was changed value. I saw some code here
private void Form1_Load(object sender, EventArgs e)
{
foreach (Control ctrl in this.Controls)
{
if (ctrl is TextBox)
{
TextBox tb = (TextBox)ctrl;
tb.TextChanged += new EventHandler(tb_TextChanged);
}
}
}
void tb_TextChanged(object sender, EventArgs e)
{
TextBox tb = (TextBox)sender;
tb.Tag = "CHANGED"; // or whatever
}
And a guy who wrote this code says that "it can't be assigned to textboxes in Panels and Grouboxes".
So my question is as I have almost every textbox in groubox or panel, how can I see whether change was made for textboxes in panels or groupbox?
You can make your method recursive:
private void Form1_Load(object sender, EventArgs e)
{
Assign(this);
}
void Assign(Control control)
{
foreach (Control ctrl in control.Controls)
{
if (ctrl is TextBox)
{
TextBox tb = (TextBox)ctrl;
tb.TextChanged += new EventHandler(tb_TextChanged);
}
else
{
Assign(ctrl);
}
}
}
void tb_TextChanged(object sender, EventArgs e)
{
TextBox tb = (TextBox)sender;
tb.Tag = "CHANGED"; // or whatever
}
Just find a better name for the method instead of Assign.
When you have to deal with nested controls, 1 for loop can't help. You have to use some recursive method or custom stack to loop through all the controls, something like this:
private void RegisterTextChangedEventHandler(Control root){
Stack<Control> stack = new Stack<Control>();
stack.Push(root);
Control current = null;
while(stack.Count>0){
current = stack.Pop();
foreach(var c in current.Controls){
if(c is TextBox) ((TextBox)c).TextChanged += textChanged;
stack.Push(c);
}
}
}
private void textChanged(object sender, EventArgs e){
//....
}
//Use it
RegisterTextChangedEventHandler(yourForm);//Or your container ....
You need another loop for the groupbox and panels, you can use this code:
private void addEvents(Control.ControlCollection ct)
{
foreach (Control ctrl in ct)
{
if (ctrl is TextBox)
{
TextBox tb = (TextBox)ctrl;
tb.TextChanged += new EventHandler(tb_TextChanged);
}
else if (ctrl is GroupBox || ctrl is Panel) addEvents(ctrl.Controls);
}
}
private void Form1_Load(object sender, EventArgs e)
{
addEvents(this.Controls);
}
void tb_TextChanged(object sender, EventArgs e)
{
TextBox tb = (TextBox)sender;
tb.Tag = "CHANGED"; // or whatever
}

Unable to drag and drop text from DataGridView to TextBox C#

I have been using code that others online have supplied but for some reason it won't let me drag items from the datagridview to the textbox. I highlight a row in the dataGridView and try to drag it to the textbox but nothing happens. I have also enabled the drop property for the textBox but still no difference. Here's the code that I am using:
private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
DataGridView.HitTestInfo info = dataGridView1.HitTest(e.X, e.Y);
if (info.RowIndex >= 0)
{
if (info.RowIndex >= 0 && info.ColumnIndex >= 0)
{
string text = (String)
dataGridView1.Rows[info.RowIndex].Cells[info.ColumnIndex].Value;
if (text != null)
dataGridView1.DoDragDrop(text, DragDropEffects.Copy);
}
}
}
}
private void textBox1_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(System.String)))
{
textBox1.Text = (System.String)e.Data.GetData(typeof(System.String));
}
}
private void textBox1_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Copy;
}
Here is a small sample that i have done to give you an idea on how to do this... works perfectly for me. I used WinForms here. If WPF, there may be some more events you will need to register to in order for the drag+drop to register...
Note that you will want to add more code here and there to perform what you really want to do when you drag an item from one control to the other.
public partial class Form1 : Form
{
private Rectangle dragBoxFromMouseDown;
private int rowIndexFromMouseDown;
private int rowIndexOfItemUnderMouseToDrop;
private DataGridViewRow draggedrow;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
List<StringValue> Items = new List<StringValue>() { new StringValue("1"), new StringValue("2"), new StringValue("3"), new StringValue("4"), new StringValue("5"), new StringValue("6") };
this.dataGridView1.DataSource = Items;
}
private void dataGridView1_MouseMove(object sender, MouseEventArgs e)
{
if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
{
// If the mouse moves outside the rectangle, start the drag.
if (dragBoxFromMouseDown != Rectangle.Empty &&
!dragBoxFromMouseDown.Contains(e.X, e.Y))
{
// Proceed with the drag and drop, passing in the list item.
DragDropEffects dropEffect = dataGridView1.DoDragDrop(
dataGridView1.Rows[rowIndexFromMouseDown],
DragDropEffects.Move);
}
}
}
private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
{
// Get the index of the item the mouse is below.
rowIndexFromMouseDown = dataGridView1.HitTest(e.X, e.Y).RowIndex;
if (rowIndexFromMouseDown != -1)
{
// Remember the point where the mouse down occurred.
// The DragSize indicates the size that the mouse can move
// before a drag event should be started.
Size dragSize = SystemInformation.DragSize;
// Create a rectangle using the DragSize, with the mouse position being
// at the center of the rectangle.
dragBoxFromMouseDown = new Rectangle(new Point(e.X - (dragSize.Width / 2),
e.Y - (dragSize.Height / 2)),
dragSize);
this.draggedrow = this.dataGridView1.CurrentRow;
}
else
// Reset the rectangle if the mouse is not over an item in the ListBox.
dragBoxFromMouseDown = Rectangle.Empty;
}
private void dataGridView1_DragOver(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Move;
}
private void textBox1_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Move;
}
private void textBox1_DragDrop(object sender, DragEventArgs e)
{
this.textBox1.Text = (string)this.draggedrow.Cells["Value"].Value;
}
}
public class StringValue
{
public StringValue(string s)
{
_value = s;
}
public string Value { get { return _value; } set { _value = value; } }
string _value;
}
can't you use DataGridViewCellMouseEventArgs e instead of hittest for getting row index in dataGridView1_CellMouseDown. below is your code modified hope this helps
private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
if (e.RowIndex >= 0)
{
if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
{
string text = (String)
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
if (text != null)
dataGridView1.DoDragDrop(text, DragDropEffects.Copy);
}
}
}
}
private void textBox1_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(System.String)))
{
textBox1.Text = (System.String)e.Data.GetData(typeof(System.String));
}
}
private void textBox1_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Copy;
}

Assigning event TextChanged to all textboxes in Form

Hello I was wondering how can I keep an eye on all textboxes in Form whether in any of them was changed value. I saw some code here
private void Form1_Load(object sender, EventArgs e)
{
foreach (Control ctrl in this.Controls)
{
if (ctrl is TextBox)
{
TextBox tb = (TextBox)ctrl;
tb.TextChanged += new EventHandler(tb_TextChanged);
}
}
}
void tb_TextChanged(object sender, EventArgs e)
{
TextBox tb = (TextBox)sender;
tb.Tag = "CHANGED"; // or whatever
}
And a guy who wrote this code says that "it can't be assigned to textboxes in Panels and Grouboxes".
So my question is as I have almost every textbox in groubox or panel, how can I see whether change was made for textboxes in panels or groupbox?
You can make your method recursive:
private void Form1_Load(object sender, EventArgs e)
{
Assign(this);
}
void Assign(Control control)
{
foreach (Control ctrl in control.Controls)
{
if (ctrl is TextBox)
{
TextBox tb = (TextBox)ctrl;
tb.TextChanged += new EventHandler(tb_TextChanged);
}
else
{
Assign(ctrl);
}
}
}
void tb_TextChanged(object sender, EventArgs e)
{
TextBox tb = (TextBox)sender;
tb.Tag = "CHANGED"; // or whatever
}
Just find a better name for the method instead of Assign.
When you have to deal with nested controls, 1 for loop can't help. You have to use some recursive method or custom stack to loop through all the controls, something like this:
private void RegisterTextChangedEventHandler(Control root){
Stack<Control> stack = new Stack<Control>();
stack.Push(root);
Control current = null;
while(stack.Count>0){
current = stack.Pop();
foreach(var c in current.Controls){
if(c is TextBox) ((TextBox)c).TextChanged += textChanged;
stack.Push(c);
}
}
}
private void textChanged(object sender, EventArgs e){
//....
}
//Use it
RegisterTextChangedEventHandler(yourForm);//Or your container ....
You need another loop for the groupbox and panels, you can use this code:
private void addEvents(Control.ControlCollection ct)
{
foreach (Control ctrl in ct)
{
if (ctrl is TextBox)
{
TextBox tb = (TextBox)ctrl;
tb.TextChanged += new EventHandler(tb_TextChanged);
}
else if (ctrl is GroupBox || ctrl is Panel) addEvents(ctrl.Controls);
}
}
private void Form1_Load(object sender, EventArgs e)
{
addEvents(this.Controls);
}
void tb_TextChanged(object sender, EventArgs e)
{
TextBox tb = (TextBox)sender;
tb.Tag = "CHANGED"; // or whatever
}

dataGridView Context menu function

I have added this code to my forum:
private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
ContextMenu a = new ContextMenu();
a.MenuItems.Add(new MenuItem("Google"));
a.MenuItems.Add(new MenuItem("Yahoo"));
int currentMouseOverRow = dataGridView1.HitTest(e.X, e.Y).RowIndex;
if (currentMouseOverRow >= 0)
{
a.MenuItems.Add(new MenuItem(string.Format("", currentMouseOverRow.ToString())));
}
a.Show(dataGridView1, new Point(e.X, e.Y));
}
}
private void dataGridView1_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
{
currentMouseOverRow = e.RowIndex;
}
private void dataGridView1_CellMouseLeave(object sender, DataGridViewCellEventArgs e)
{
currentMouseOverRow = -1;
}
But how do I add the function to the context menu option?
For google,
Process.Start("https://www.google.com");
For yahoo,
Process.Start("https://www.yahoo.com");
etc.
Why not add your ContextMenu right when your Form loads rather than every time that the user right click your DataGridView which means that you have to add the Context Menu every time the user rights click your DatGridView.
Secondly, instead of ContextMenu make a ContextMenuStrip instead which more at home with DataGridView. So, your code would look like:
ContextMenuStrip a = new ContextMenuStrip();
public Form1()
{
InitializeComponent();
this.Load += new EventHandler(Form1_Load);
}
void Form1_Load(object sender, EventArgs e)
{
Image img = null;
a.Items.Add("Google", img, new System.EventHandler(ContextMenuClick));
a.Items.Add("Yahoo", img, new System.EventHandler(ContextMenuClick));
dataGridView1.ContextMenuStrip = a;
}
Then your EventHandler would look like this:
private void ContextMenuClick(Object sender, System.EventArgs e)
{
switch (sender.ToString().Trim())
{
case "Google":
Process.Start("https://www.google.com");
break;
case "Yahoo":
Process.Start("https://www.yahoo.com");
break;
}
}
And your DataGridView Mouse Click handler would look this:
void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
int currentMouseOverRow = dataGridView1.HitTest(e.X, e.Y).RowIndex;
if (currentMouseOverRow >= 0)
{
a.Items.Add(string.Format("", currentMouseOverRow.ToString()));
}
a.Show(dataGridView1, new Point(e.X, e.Y));
}
}
You have to use ClickEvent for your menu items:
//menu items constructor
a.MenuItems.Add(new MenuItem("Google", new System.EventHandler(this.MenuItemClick)));
a.MenuItems.Add(new MenuItem("Yahoo", new System.EventHandler(this.MenuItemClick)));
private void MenuItemClick(Object sender, System.EventArgs e)
{
var m = (MenuItem)sender;
if (m.Text == "Google")
{
Process.Start("https://www.google.com");
}
}

Auto highlight text in a textbox control

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;

Categories

Resources