c# same command for different textboxes - c#

I was wondering if I could do this, but but all in one function. As in if I could clear every all textboxes on the event "enter" without creating multiple functions.
private void textBox4_Enter(object sender, EventArgs e)
{
textBox4.Clear();
}
private void textBox3_Enter(object sender, EventArgs e)
{
textBox3.Clear();
}
private void textBox5_Enter(object sender, EventArgs e)
{
textBox5.Clear();
}
private void textBox2_Enter(object sender, EventArgs e)
{
textBox2.Clear();
}
private void textBox1_Enter(object sender, EventArgs e)
{
textBox1.Clear();
}

Build the method like this:
private void textBox_Enter(object sender, EventArgs e)
{
(sender as TextBox)?.Clear();
}
And then set it up like this:
public MyForm()
{
//This is your form's constructor
InitializeComponent();
textBox1.Enter += textBox_Enter;
textBox2.Enter += textBox_Enter;
textBox3.Enter += textBox_Enter;
textBox4.Enter += textBox_Enter;
textBox5.Enter += textBox_Enter;
}
But for such a simple method, you haven't really gained anything. I'd also find it quite annoying to have a TextBox clear like that.

Yes, you can use the same method for all events: the textbox that triggers the event will be the sender parameter of the method. All you have to do is cast it to TextBox and call Clear on it:
private void textBox_Enter(object sender, EventArgs e)
{
(sender as TextBox).Clear();
}

I would tend to avoid creating extra methods at all by doing this:
foreach (var textBox in new [] { textBox1, textBox2, textBox3, textBox4, textBox5 })
{
var tb = textBox;
tb.Enter += (_s, _e) => tb.Clear();
}

Related

Way to simplify functions?

Is there a way to create a class or something that can contain all these different textboxes. I just want to know if this is the most efficient way I can code this.
private void textBox1_Click(object sender, EventArgs e)
{
textBox1.Text = "";
}
private void textBox2_Click(object sender, EventArgs e)
{
textBox2.Text = "";
}
private void textBox3_Click(object sender, EventArgs e)
{
textBox3.Text = "";
}
private void textBox4_Click(object sender, EventArgs e)
{
textBox4.Text = "";
}
private void textBox5_Click(object sender, EventArgs e)
{
textBox5.Text = "";
}
Don't create separated event handlers for each TextBoxes. Instead, create a combined event for all the TextBoxes: textBox1..textBox5.
Then
private void textBoxs_Click(object sender, EventArgs e)
{
if (sender is TextBox box) box.Text = "";
}
You can add the event handler to all the TextBoxes on load, eg
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
foreach(var tb in this.Controls.OfType<TextBox>())
{
tb.Click += (sender, eventArgs) => ((TextBox)sender).Text = "";
}
}

EventHandler for all controls in form

In my code I want to perform some actions when some controls are focused. So instead of having one handler for each control i was wondering if there could be any way of adding all controls to the handler and inside the handler function perform the desired action.
I have this:
private void tb_page_GotFocus(Object sender, EventArgs e)
{
tb_page.Visible = false;
}
private void tb_maxPrice_GotFocus(Object sender, EventArgs e)
{
tb_maxPrice.Text = "";
}
private void tb_maxPrice_GotFocus(Object sender, EventArgs e)
{
tb_maxPrice.Text = "";
}
I want this:
private void AnyControl_GotFocus(Object sender, EventArgs e)
{
if(tb_page.isFocused == true)
{
...
}
else if (tb_maxPrice.isFocused == true)
{
...
}
else
{
...
}
}
Is this possible? How could I do it? Thanks a lot.
Iterate your controls in your form or panel and subscribe to their GotFocus Event
private void Form1_Load(object sender, EventArgs e)
{
foreach (Control c in this)
{
c.GotFocus += new EventHandler(AnyControl_GotFocus);
}
}
void AnyControl_GotFocus(object sender, EventArgs e)
{
//You'll need to identify the sender, for that you could:
if( sender == tb_page) {...}
//OR:
//Make sender implement an interface
//Inherit from control
//Set the tag property of the control with a string so you can identify what it is and what to do with it
//And other tricks
//(Read #Steve and #Taw comment below)
}

How do I define custom eventargs for an event?

I would like to create custom Eventargs for a series of events. I am using a third party X/Y scope where I plot Strength vs frequency. This scope has the ability to place "Markers" on it which are just little triangles at various frequencies. These markers support events such as when the mouse enters the marker, a click is performed, and the mouse leaves the marker. So for two markers, here is the code:
private void createEvents()
{
this.scope2.MarkerGroups[0].Click += new EventHandler(Marker0_Click);
this.scope2.MarkerGroups[0].MouseEnter += new EventHandler(Marker0_Enter);
this.scope2.MarkerGroups[0].MouseLeave += new EventHandler(Marker0_Leave);
this.scope2.MarkerGroups[1].Click += new EventHandler(Marker1_Click);
this.scope2.MarkerGroups[1].MouseEnter += new EventHandler(Marker1_Enter);
this.scope2.MarkerGroups[1].MouseLeave += new EventHandler(Marker1_Leave);
}
// And now the event handlers
private void Marker0_Click(object sender, EventArgs e)
{
//do something;
}
private void Marker0_Enter(object sender, EventArgs e)
{
//do something
}
private void Marker0_Leave(object sender, EventArgs e)
{
// do something
}
private void Marker1_Click(object sender, EventArgs e)
{
//do something;
}
private void Marker1_Enter(object sender, EventArgs e)
{
//do something
}
private void Marker1_Leave(object sender, EventArgs e)
{
// do something
}
Now this is fine for two markers....but I need 80 of them. I could just write the whole thing out but there has to be a better way. So I started like this:
private void createMarkerEvents()
{
for (int i = 0; i < 80; i++)
{
this.scope2.MarkerGroups[i].Click += new EventHandler(Marker_Click);
this.scope2.MarkerGroups[i].MouseEnter += new EventHandler(Marker_Enter);
this.scope2.MarkerGroups[i].MouseLeave += new EventHandler(Marker_Leave);
}
}
private void Marker_Click(object sender, EventArgs e)
{
//do something;
}
private void Marker_Enter(object sender, EventArgs e)
{
//do something
}
private void Marker_Leave(object sender, EventArgs e)
{
// do something
}
So the question is how can I pass the actual marker number from the events to the event handlers?
There has got to be a way.
Thanks, Tom
If you want to identify marker group you may cast object sender to a MarkerGroup object
private void AnyMarker_Click(object sender, EventArgs e)
{
MarkerGroup group = (MarkerGroup)sender;
int indexOfMarkerGroup = this.scope2.MarkerGroups.IndexOf(group);
//do something;
}
OFF: You should define a custom EventArgs class:
public class MyEventArgs : EventArgs
{
public int MyCustomProperty {get;set;}
}
Then use it in your event:
public event EventHandler<MyEventArgs> ButtonPressed;
Fire event using custom args:
if(ButtonPressed != null)
{
ButtonPressed(this, new MyEventArgs { MyCustomProperty = 1 });
}
EDIT
Full example:
private void createMarkerEvents()
{
for (int i = 0; i < 80; i++)
{
this.scope2.MarkerGroups[i].Click += new EventHandler(Marker_Click);
this.scope2.MarkerGroups[i].MouseEnter += new EventHandler(Marker_Enter);
this.scope2.MarkerGroups[i].MouseLeave += new EventHandler(Marker_Leave);
}
}
private void Marker_Click(object sender, EventArgs e)
{
// When markergroup fires and event, it passes reference to itself as `sender` parameter
// so we can get access it
MarkerGroup mg = (MarkerGroup)sender; // this marker has fired a click event
// Now you know which marker has fired event
// if you want to determine it's index in MarkerGroups collection:
int index = this.scope2.MarkerGroup.IndexOf(mg);
// now you know MarkerGroup and it's index
}
private void Marker_Enter(object sender, EventArgs e)
{
//do something
}
private void Marker_Leave(object sender, EventArgs e)
{
// do something
}

Handle Application.Exit(CancelEventArgs) in C#

Simply put, how can I subscribe to and handle the following event?
System.Windows.Forms.Application.Exit(new System.ComponentModel.CancelEventArgs(true));
because apparently this is not going to give me my CancelEventArgs:
Application.ApplicationExit += new EventHandler(ApplicationExitHandler);
private void ApplicationExitHandler(Object sender, EventArgs e)
{
...
}
Try to put Event inside the Form1.Designer.cs
private void InitializeComponent()
{
//.......... UI iniatilization
System.Windows.Forms.Application.ApplicationExit +=new System.EventHandler(ApplicationExitHandler);
}
In Form1.cs
private void ApplicationExitHandler(Object sender, EventArgs e)
{
//.............
}

How to call a button click event from another method

How can I call SubGraphButton_Click(object sender, RoutedEventArgs args) from another method?
private void SubGraphButton_Click(object sender, RoutedEventArgs args)
{
}
private void ChildNode_Click(object sender, RoutedEventArgs args)
{
// call SubGraphButton-Click().
}
You can easily do it by the following piece of code (assuming that name of your button is btnButton):
btnButton.PerformClick();
You can call the button_click event by simply passing the arguments to it:
private void SubGraphButton_Click(object sender, RoutedEventArgs args)
{
}
private void ChildNode_Click(object sender, RoutedEventArgs args)
{
SubGraphButton_Click(sender, args);
}
you can call the button_click event by passing..
private void SubGraphButton_Click(object sender, RoutedEventArgs args)
{
}
private void ChildNode_Click(object sender, RoutedEventArgs args)
{
SubGraphButton_Click(sender, args);
}
Also without passing..
private void SubGraphButton_Click(object sender, EventArgs args)
{
}
private void Some_Method() //this method is called
{
SubGraphButton_Click(new object(), new EventArgs());
}
You can perform different approaches to work around this. The best approach is, if your both buttons are suppose to do the same job, you can define a third function to do the job. for example :
private void SubGraphButton_Click(object sender, RoutedEventArgs args)
{
myJob()
}
private void ChildNode_Click(object sender, RoutedEventArgs args)
{
myJob()
}
private void myJob()
{
// Your code here
}
but if you are still persisting on doing it in your way, the best action is :
private void SubGraphButton_Click(object sender, RoutedEventArgs args)
{
}
private void ChildNode_Click(object sender, RoutedEventArgs args)
{
SubGraphButton_Click.PerformClick();
}
In WPF, you can easily do it in this way:
this.button.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
Usually the better way is to trigger an event (click) instead of calling the method directly.
private void PictureBox1_Click(object sender, EventArgs e)
{
MessageBox.Show("Click Succes");
}
private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
PictureBox1_Click(sender, e); //or try this one "this.PictureBox1_Click(sender, AcceptButton);"
}
}
You can simply call it:
SubGraphButton_Click(sender, args);
Now, if your SubGraphButton_Click does something with the args, you might be in trouble, but usually you don't do anything with them.
For me this worked in WPF
private void Window_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
RoutedEventArgs routedEventArgs = new RoutedEventArgs(ButtonBase.ClickEvent, Button_OK);
Button_OK.RaiseEvent(routedEventArgs);
}
}
Use InvokeOnClick event. it works even if the button is invisible/disabled
A simple way to call it from anywhere is just use "null" and "RoutedEventArgs.Empty", like this:
SubGraphButton_Click(null, RoutedEventArgs.Empty);
For WPF:
YourButtonName.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent));
Add it to the instance of the Click delegate:
ChildNode.Click += SubGraphButton_Click
which is inkeeping with the pattern .NET events follow (Observer).
For people wondering, this also works for button click.
For example:
private void btn_Click(object sender, EventArgs e)
{
MessageBox.Show("Test")
}
private void txb_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13)
{
btn_Click(sender, e);
}
When pressing Enter in the textfield(txb) in this case it will click the button which will active the MessageBox.
we have 2 form in this project.
in main form change
private void button1_Click(object sender, EventArgs e)
{
// work
}
to
public void button1_Click(object sender, EventArgs e)
{
// work
}
and in other form, when we need above function
private void button2_Click(object sender, EventArgs e)
{
main_page() obj = new main_page();
obj.button2_Click(sender, e);
}

Categories