Why does GotFocus event keep deleting itself from Designer? - c#

I wanted to add a GotFocus event to a Windows Forms Textbox, so I used the method described in this question; it works, but after I run my application a couple of times the piece of code deletes itself and I don't know why.
This is the code that keeps deleting itself:
txtID.GotFocus += txtID_GotFocus;

It disappears because you don't use conventions that are used by WinForms designer when you add event handlers.
It doesn't matter whether you use GotFocus or Enter event. If you (in your Designer.cs) manually add event handler this way:
txtID.Enter += txtID_Enter;
then it would always disappear from designer next time you move control on designer surface.
You must add event handlers this way:
txtID.GotFocus += new System.EventHandler(txtID_Focus);
txtID.Enter += new System.EventHandler(txtID_Enter);
and nothing would disappear because it's the way designer expects code to be.

Surely it's another evidence about why you should not touch designer generated code and should pay attention to this warning: do not modify the contents of this method with the code editor.
As a workaround use Enter event instead (which is recommended). Also you can assign the handler in your Load event of form.
EDIT
The reason is correctly mentioned by nikita, it's because you didn't use designer conventions. For more information see his answer.

Related

C# Form Application on click event

Please help me to fix this problem in c#. Every time i accidentally click any Button,Text Box etc. it will go to the source code and when i delete the code, debug wont run, but when i put comment sign /* comment*/ the application will run.
Any one can help me on how to remove on click event.
this is what i want to remove
private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
{ }
Every time i delete this debug will prompt me. but when i using VB i can easily delete this no need to remove the button or txtbox etc.
Basically when you double click a control, the designer automatically create a the event handler.
It also automatically assigns the event handler to the control. It makes this change in the designer.cs file of your form. This is handeled for you.
Unfortunately, when you remove the code you pointed out, the function no longer exists. Therefore, the solutions fails to build because the reference to the function still exist in the. Designer.cs file.
You need to remove the reference in the designer.cs file:
"If you click on a control in the Form Designer, you see a list of event handlers that the designer is associating with the control in the Properties Window. Click on the lightning bolt at the top of the Window to see a listing of events. You will see method names next to events that the Form Designer is writing code for in the designer.cs file. Simply erase the name of the method for the event you wish to disconnect, hit Enter, done."
- https://social.msdn.microsoft.com/Forums/vstudio/en-US/a6f25488-b761-437f-8a65-e7e51dd4b382/remove-event-handler?forum=csharpgeneral
You would not have to do this in VB.net, as VB.net uses the handles command whereas c# performs a method like so:
button1.Click += new EventHandler(button1_Click);
Just simply remove the event from your element before deleting the method in your code:
There will be a line in form.designer.cs class just remove that.
comboBox3.SelectedIndexChanged+=new eventargs(comboBox3_SelectedIndexChanged);
Moreover, windows forms use CodDom to write a code to you have to be careful hope this will help you to learn more about creating windows form application.
https://learn.microsoft.com/en-us/dotnet/framework/winforms/controls/how-to-add-controls-to-windows-forms

How do i remove an event from the code without manually deleting it?

Sometimes when you accidently double click on events it generates the events event method and add and event handler in the InitializeComponent() of the form.
So when I want to delete the event, I have to delete code in two places, the event method it self and the event handler in to InitializeComponent(). But is there away to do this without deleting code manually?
If you have have not edited the event handler body, you can simple remove the event using VS Designer. For this select Events in Properties window and remove the handler that you don't need.
However, if you have edited the event handler (i.e. the body contains some code or comments). You can still remove the event using above step. But from the cs file you have to manually delete the method. This helps to refrain from designer generated code (and possibility of messing it up).

In C#, how can you easily change the name of an event handler?

In VS2008, if I double click on the event handler VS creates a default event handler with a default name, e.g. combobox1_SelectedIndexChanged.
Say, for example, i now rename combobox1 to cbStatus. It still has the same event handler, so i now change that to cbStatus_SelectedIndexChanged.
Is there a way, where VS can change the initial combobox1_SelectedIndexChange to cbStatus_SelectedIndexChange rather than generate a new cbStatus event handler in addition to the old event handler? Because every time i have to cut and paste the code to the new event handler and then delete the old one.
In addition, if i have defined the initial event handler and then no longer require the handler, i cannot simply delete the handler from code, as the form designer then complains that it cant find the original event handler. Is there a way where VS can automatically remove the assignment of the event handler from the form designer?
I seem to be spending all day cutting and pasting, and deleting event handler assignments from the forms designer code.
When you rename the control, you should rename the event handler too. The proper way to do this is by refactoring the code.
To do this, just right-click the name of the event handler in the Visual Studio code editor and choose Refactor -> Rename... That will allow you to automatically change the name of it everywhere it's used.
In the case of an event handler, it's probably only used in one other place (the point in code where it's added to the event), so it's not too much trouble to change it manually. You can apply this technique to pretty much anything, though, making it extremely useful when something you're changing is referred to from several different places.
You just have to find the place in the generated code where the combobox1_SelectedIndexChange method is declare and change the name to cbStatus_SelectedIndexChange.
After you change the method name, you also have to update the line where you register the handler:
cbStatus.SelectedIndexChange += new
SelectedIndexChangeEventHandler(cbStatus_SelectedIndexChange);
Just type the new name, then recompile. By this I mean - Change
protected void combobox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
to
protected void renamedcombobox_SelectedIndexChanged(object sender, EventArgs e)
{
}
and then recompile
Visual Studio will throw a compile-time error, because the method that is expected is no longer there.
Double-click on the error in the Output window to go to the assignment of the error handler, and change the error handler there to match the new function name.
Edit - added
The above step will jump you to the line of code described in Justin's answer...
End Edit
I know that's clear as mud, but try it and you'll figure it out with little or no difficulty.
If you single-click instead of double-clicking to automatically create the event handler, you can specify the handler name you want. You could make it something like "SelectedStatusChangedHandler", which is independent of the combobox's variable name. Then press 'enter' and let VS create the handler for you.

How do I conserve program functionality and code after moving all controls into a tab control?

I had a working program (Windows Forms Project) complete with buttons, labels, textboxes e.t.c. and the underlying code.
In an attempt to shortcut my work, I decided to add tab controls and move everything in my main form into tab 1 (cut and pasted).
As you can imagine it didn't work. I then got rid of the tab conrol and pasted everything back into the main form but the program doesn't work anymore.
Can someone tell me what's wrong please?
I'm working in MS V studio 2008 express
Thanks.
I have done this many times, but I usually just drag them into the TabControl. Maybe in the cut and paste operation your controls have become unwired from the event declarations.
The event handlers that you coded are still there. However, they are not associated with the control any more. I'm not sure if you're using VB.Net or C#, but the fix is the same - it's manual and tedious if you have a bunch of controls, but not too difficult. Here are the instructions for fixing a single button control, and you'll have to apply the concepts across the board.
These instructions are specific to C#. I can give you VB instructions as well as I've done this plenty of times.
Double click on the button to generate a new event handler. If the button is named Button1, the original event handler was probably called Button1_Click. Now it should be Button1_Click1.
Delete the Button1_Click1 function and compile. You'll get errors and if you doible-click on the error in the error pane it will take you to the form,designer.cs file to a line that looks like:
this.Button1.Click += new System.EventHandler(this.Button1_Click1);
Change this to
this.Button1.Click += new System.EventHandler(this.Button1_Click);
to point to the previously existing event handler, and the event handler will be fixed.
Possibly some of the events had code lost.
If you do it again it will probably work.
For an alternative method see my message

Event Handling in winforms with multiple controls

Lets say we have a form consisting of 20+ controls, for example buttons.
We want to create handlers for the On-click event for all of them.
The usual way is to go to the designer and double-click each button to have it automatically create the function.
Another way is to create them yourself in code, after the InitializeComponent() function.
Is the difference between the two?
1) In performance
2) In speed
3) Garbage collecting
The first way is easy but lately I've been thinking about the second because its easy to see (in one place) what controls have what events handled without going to the designer which is a real pain if you have the controls cluttered...
Creating them through the designer is exactly the same as defining them in code yourself.
What actually happens is they are placed within the InitializeComponent() method on the form, which is normally in the designer.cs file. So it's there, it's just a little more hidden from the developer.
This means that neither performance/speed nor garbage collection will be affeted in anyway :)
As the other answers stated, there is little to choose between the tow methods other then coding style.
I have worked on a project where the Buttons themselves were attributed data that allowed a generic event handler to determine the action required. This alows the Event Handler code to be nice and simple e.g.
foreach(Control ctrl in this.Controls)
{
if(ctrl is Button)
{
(ctrl as Button).Click += // generic Event handler
}
}
The downside of this approach is that it tightly couples the button with the event handler code. But in a limited scope application with a set of buttons that perform the same function, this could be a useful techinque.
There's no difference in performance speed or garbage collection. Whether you write the event hander button.OnClick += MyHandler or you double click in the designer and he generates that for you, it's just the same.
There might be a difference in typing button.OnClick += MyHandler and the Visual Studio generated button.OnClick += new EventHandler(MyHandler). Since there's a constructor involved. But that's just a marginal difference.
Why would there be any difference ?
When you doubleclick the button in the designer, to create an eventhandler, VS.NET will generate code to attach the eventhandler to the Click event.
Actually, the generated code will be the same as the code that you'll write to attach the eventhandler to the event.

Categories