Do I have to define an event in this case? - c#

I've got a form with several controls (to make things simple, say it's a couple of textboxes), which I need to be updated by clicking on two buttons - a Forward button and a Backwards button.
Now, the general idea is that the information to be displayed is stored in some kind of array of objects, and is shown according to the value of some counter. That is, a user clicks on the Forward button -> the counter is incremented -> the corresponding array item is shown on the form. Same goes for the Backwards button.
So, the question is - should I define any specific event in this case? Or is it sufficient to use the standard
private void button1_Click(Object sender, EventArgs e) {}
event which is provided when double-clicking on a button control? I mean, what would be the right thing to do?
I think it's a pretty dumb question, still I appreciate your advice here, thanks in advance!

The click event is an ok place for that logic, however, it's a good practice to extract that forward/backward logic in a separate method (maybe you'll want to go forward by pressing the right arrow?) to something like this:
private void btnForward_Click(Object sender, EventArgs e)
{
GoForward();
}
private void GoForward()
{
// the forwarding code here
}
And, make a habit of naming controls as early as possible, because VS uses the control name to name the event handler, and button1_Click is not very descriptive :)

Related

c# how do i detect when a user clicks anywhere inside a form

I need to have something happen when a user clicks anywhere inside the form. I don't know much about c# and I have tried looking it up but I just can't find an answer to this exact question.
try this
1 --> go to form properties.
2 --> find Click event.
3 --> double Click it.
code here
There's things called events
so when the event is happen the code will work
for ex:
Click : when I 'click', the code will happen and that's what are you looking for
private void Form1_Click(object sender, EventArgs e)
{
MessageBox.Show("hello world!");
}
All you have to do is select the event you want from the properties tab and double click on it and write the code you want

Using a Picture Box as a button, how do I ignore/disable double-click events?

I'm having some difficulty using picture boxes as buttons. I'd like to have custom button graphics rather than using the plain-old windows forms Button control.
It works pretty well, except the buttons seem to lag when a single button is pressed rapidly. I'd like the OnClick method to be called immediately every time the Picture Box is clicked, but it seems to be registering a double-click event, even though I am not using that event.
The short version is I'd like to:
(Ideal) Disable the double-click event, since it appears this is what the Control is waiting for on every alternating click of the Picture Box and I never use it. Or,
(Acceptable) Write a generic DoubleClick event I can use for all Picture Boxes I plan to use as buttons.
I did write up a test program which shows that this is, in fact, what's happening. I wrote a MouseUp event that increments a counter by 1, and also added a OnClick even that increments a different counter by 1. When rapidly clicking the Picture Box linked to these events, the MouseUp counter is exactly double that of the OnClick counter.
I then added a DoubleClick event that calls the OnClick event. This, although not ideal, solves the problem perfectly well. If there is a way to write a generic DoubleClick event that all buttons could use, I think this would be acceptable.
Right now my DoubleClick event is just
private void pb_DoubleClick(object sender, EventArgs e)
{
pbOK_Click(sender, e); //This needs to be generic
}
I'd like to at least replace the DoubleClick line with something like
private void pb_DoubleClick(object sender, EventArgs e)
{
(Sender.ToString)_Click(sender, e); // Doesn't work quite like this.
}
I could write a special DoubleClick event for each Picture Box individually, but that is far from ideal and seems quite cumbersome, so I would prefer not to do that if it isn't necessary.
This is my first posted question, so thanks to anyone who takes the time to read this. Any advice would be greatly appreciated.
EDIT: This program is being developed for Windows CE, so the properties and events options for the objects is quite limited. I still may be missing something, but as far as I can tell the Properties list for buttons goes straight from GenerateMember to Location, with none of the Image options available. I apologize for not stating the target platform in the original post.
It is done with the Control.SetStyle() method, like this:
using System;
using System.Windows.Forms;
class MyButton : PictureBox {
public MyButton() {
this.SetStyle(ControlStyles.StandardDoubleClick, false);
}
}
Okay, my original answer was trash. My update:
Here's a link on how to get a controls Method name:
Link
In the link it has a Control c. To get your control (sender) use the following:
PictureBox picbox = (PictureBox) sender;
Next, call a method using a string(your class.Method.Name): Link
Now that should work. Hope it does.
Why don't you create your own control? This way, you don't have to do anything to get the behavior you want.
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public class ButtonPictureBox : PictureBox
{
protected override void OnDoubleClick(System.EventArgs e)
{
OnClick(e);
}
}
}
I don't know if this is possible on Windows CE though.
If you also want to hide the DoubleClick event in the form designer, you can add this to the class:
[Browsable(false)]
public new event EventHandler DoubleClick;

Registering to event and create a new method at run time - c#

How can I register to event and do some actions at runtime?
For example when the user click on a button I want to register to OnMyEvent and run MyFunc that let's say initialize some textBox with the OnMyEvent args.
I'm using winforms and .NET 4.
EDIT
Maybe I was unclear... I need the ability to register to existing event and add a new method that will run when the event will fire. All at runtime.
EDIT2
i'll try to give an example...
lets say that i have a class named "A" that have many events OnDataRecived OnDataSend etc...
when the application running the user can choose form a combobox event name to register (i got the events list via reflection because they not constracts, they are generated from xml file) and which data to update when the choosed event is fired.
so for the example the user choose to register to the OnDataReceived and he choose to update property named DataStream. some code...
in run time upon user choosing:
A.OnDataReceived += (s,e) => MyRunTimeMethod(s,e);
private void MyRunTimeMethod(object sender, EventArgs e)
{
DataStream = e.Data.Value
}
You are asking how to create a method dynamically at runtime - once you have a reference to that method in a delegate, the question of how to register it to an event is trivial.
MSDN describes how to do this with MSIL instructions. I doubt that's what you're looking for, but it is an option.
The C# FAQ blog has a much more interesting solution using expression trees. I suppose this is the one you were referring to by originally tagging your post with expression-tree.
But I would reconsider using dynamic methods at all. How exactly is the user going to specify what action to perform on the event of his choice? I suspect that the options are limited enough that you can get by with something simpler:
protected void btnRegister_Click(object sender, EventArgs e) {
switch (cmbEvents.SelectedText) {
case "OnLoad":
MyControl.OnLoad += (s, e) => SomeSelectedControl.Text = SomeInputControl.Text;
break;
//... other cases
}
}
If you're using windows forms, double clicking a button will bring you to a created on_click event. If you bring up the properties window for the button, theres an events tab. Viewing this will show you which events are available for a control.
I found the best way to understand this, was to look at the code created when adding the events.
Update:
As noted, I completely missed the point with my answer. The syntax for subscribing to an event at runtime is the same way as it's done on form Initialize. So I don't get any terminology wrong, here's the link to the msdn documentation;
http://msdn.microsoft.com/en-us/library/ms366768.aspx
What you want to achieve, does not require you to "Register to event at run time".
If button1 is the button of interest here, simply use.
button1.Click += buton1_ClickHandler;
button1_ClickHandler should be defined in the same class as your button1. and it should have the signature of the RoutedEventHandler. So, it should be
private void button1_ClickHandler(object sender, RoutedEventArgs e)
{
//method code here
}

Replacing the content of textBox1 with the contents of textBox2

I'm quite sure I'm missing some sort of really obvious solution to this. It might be my state of rank newbie, but I am completely lost at this point.
Essentially, I need to create a WinForm that will allow the user to input text in textBox1 and textBox2. Then, at the click of button1, the text in textBox2 replaces that in textBox1. From what I can tell, this needs to go into the button1_Click event.
Here's a few examples of what I've tried so far:
private void button1_Click(object sender, EventArgs e)
{
string output;
output = textBox2.Text;
textBox1.Text = output;
}
And the simplest solution I could find:
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = textBox2.Text;
}
As well as:
this.textBox1.Text = this.textBox2.Text;
None of these work. I can enter the text just fine in either textbox, but nothing happens when I actually click the button. My mother would turn me over her knee if she could hear my response to that lack of... well, response.
Like I said, I'm sure I'm missing something really obvious. But I've now consulted my textbook, Google, Bing and at least a half-dozen forums with no luck in finding anything that has let me solve this on my own. Could someone be kind enough to tell me what it is I'm doing wrong?
It sounds like your event handler is not wired in.
Go to your form designer and click on Button1, then look at the Click event and see if it says button1_Click. (The list of events is in the Properties window. Click the yellow lightning bold icon to view the events).
Alternatively, if you want to just check that the event handler is wired up properly you can open (assuming your form is called MyForm) MyForm.Designer.cs and look for this line:
this.Button1.Click += new System.EventHandler(this.button1_Click);
or something real close to that.
Did you hook the event properly? I'm betting your button1_Click doesn't get called. Put a breakpoint in it to make sure.

Tab Control Shares The same buttons Winform

I wonder If it is possible to have fixed number of buttons that is shared by different tab pages. However I don't know how to implement this. Do you guys have any idea.
Heres a screenshot of my gui so that all of you can have a clearer view of what I meant.
I want that that the list of Customers, Reservations, and Check In/out will share the buttons search, edit, delete and refresh.
Is it possible? or should I create diff buttons for every tabpage?
is it correct if i do:
private void buttonSearch_Click(object sender, EventArgs e)
{
if(tabpage.SelectedIndex == 1){ then perform action..}
if(tabpage.SelectedIndex == 2) {then perform action...}
}
You could put the buttons in a User Control, add some events to the User Control (e.g. SearchClicked, EditClicked, etc.). Put the user control outside of the tabcontrol.
Then when you change tabs (TabIndexChanged), remove event handlers from the previous tab, and add event handlers for the new tab:
private void tabControl_TabIndexChanged(object sender, EventArgs e)
{
UserControl1.EditClicked -= OldEventHandler;
UserControl1.EditClicked += NewEventHandler;
}
Yes, you can change the .Parent property of the buttons at runtime - but wouldn't it be better to just move the buttons outside the tab control?
I feel you should create different buttons for every tab page as each one operates on a different entity. If there is only one set of buttons then you will have to first check which tab page is selected and then do the operation. So you will have one big method doing lots of things.
Plus there would be extra UI code that you will have to write to move the buttons when a tab page is selected.
With different buttons you will have highly cohesive and loosely coupled code. Better design. More maintainable and manageable. Less code.

Categories