I'm converting a VB project to C#, and I notice that in vb it will call a function like:
Protected Sub WZTestResult_NextButtonClick(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.WizardNavigationEventArgs) Handles WZTestResult.NextButtonClick
which handles the next button click event for a wizard.
In c# I have to add the line:
OnNextButtonClick="WZTestResult_NextButtonClick"
on the asp.net source page or it will never hit the function. Is this a necessity in c#, or is there something that I'm overlooking or missing? Basically, is there a way in c# for it to hit that function like in VB without adding the line above in the source page?
There is no equivalent for VB's Handles keyword.
You can do it in code behind if you want, when the page is initialized
public Default() {
this.Init += (_o, _e) => {
this.Wizard.NextButtonClick += WZTestResult_NextButtonClick;
}
}
Default is the page constructor.
Generally speaking the IDE will take care of most of this for you. If you add a button to a form in the Visual Studio designer and double click on that button it will take you to the event handler for that control in the code (the click event in this case).
private void button1_Click(object sender, EventArgs e)
{
}
You'll notice that the file you're in doesn't contain the code that attaches this method to the control event. Visual Studio splits the form into a partial class that contains your code and a generated class that contains auto-generated wiring code. In the solution explorer that looks like this:
Form1.cs -> the file that you'll add code to
Form1.Designer.cs -> the auto-generated designer file
You don't want to change the .designer.cs files because changing the form in the visual designer might overwrite your changes. You'll just work in the Form1.cs file and you'll likely never even see the event assignment code.
So the answer to your question is no, with the caveat that you'll rarely ever have to add or see this code:
this.Wizard.NextButtonClick += WZTestResult_NextButtonClick;
Related
My scenario is quite simple, in fact I thought it would cause no problem but it does, can anyone help?
My MainPage begins with this:
namespace PhoneApp
{
public partial class MainPage : PhoneApplicationPage { /* snip */ }
}
Later in the page is this simple method:
private void MakeSound(object sender, MouseButtonEventArgs e)
All right, everything is fine.
But on my SettingsSample.xaml I have a ListBoxItem that calls the method MakeSoundvia SelectionChanged property. VS studio tells me that 'event handler MakeSoundis not found on class PhoneApp.SettingsSample '
The code for this page begins with:
namespace PhoneApp
{
public partial class SettingsSample : PhoneApplicationPage { /* snip */ }
}
Copying the code of the method on SettingsPage.xaml.cs doesn't work for some reason, but I feel like it should possible to use the method described on MaingePage.xaml.cs, especially since their respective code resides in the same Namespace.
I tried to add
using PhoneApp;
on SettingsSample.xaml.cs. Not exceptionally clever, but I have no other idea
Your event function should read EventClickOnMyListBox and be located in the code-behind for your page. This function would then call your makeasound function (that you can put wherever you want). And it could be called by another event or function.
There is a semantics distinction between the event itself and what the event does. Your event is not makeasound, your event will cause a sound to be made, among possible other things.
If ever you want to add a popup to add a visual effect, you'll be stuck if you called directly the makeasound function, whereas you'll just have to add a line to your EventClickOnMyListBox in the other scenario.
That's why xaml works that way, and allows you to refer only to object in the enclosing class (or if there is a way I don't know it / and never needed it). You should minimize code-behind code (this is the way of thinking of the MVVM pattern if you want to go further down this road).
Replying to your comment, here is some code to get you started:
Your event should be in the code-behind of your SettingSample page, and should call the makeasound function instead of being the makeasound function:
private void MenuItem_Click(object sender, MouseButtonEventArgs e)
{
Whatever.Myclass.MakeASound (blabla); // So typically MakeASound would be static
}
And now same thing in your main page: you do not use your private void MakeSound(object sender, MouseButtonEventArgs e) as the event for a click, but an event handler just as the one above.
Take a step back and you'll see it's very natural: you want two things to do the same. But one thing cannot be the exact same thing as the first, for language-related reasons (read about C# and XAML to understand why).
So you put your feature in a third component, accessible from the first two. And you call this component from each of them. This way, they both share access to the same feature, and everybody is happy.
Is there a way to know what parameters are needed by an event in Visual Studio 2010?
Let's say I have a DropDownList control and I want to bind a method to the "OnSelectedIndexChanged", I would do something like this
In the ASPX File:
<asp:DropDownList ID="lstMyList" runat="server" OnSelectedIndexChanged="lstMyList_SelectedIndexChanged"></asp:DropDownList>
In the codebehind:
protected void lstMyList_SelectedIndexChanged(object sender, EventArgs e)
{
...
}
Is there a way to know what parameters the method needs? (In this case, an object for the sender and an EventArgs parameter for the event.)
I know you can easily create the method by double-clicking the right event in Design Mode, but it does a mess with your code so I prefer not to use it.
Thanks!
You can find out the parameters by "going to definition" (F12) on the appropriate event, finding out what delegate type it uses, then going to definition on that. In this case the SelectedIndexChanged event has type EventHandler which is defined as follows:
[SerializableAttribute]
[ComVisibleAttribute(true)]
public delegate void EventHandler(
Object sender,
EventArgs e
)
You can also find this information by searching the web or pressing F1 and searching in the help.
I know you can easily create the method by double-clicking the right event in Design Mode, but it does a mess with your code so I prefer not to use it.
I think you should try to overcome your fear of using the designer. You are most likely wasting more time in lost productivity by not using the code generation features in Visual Studio than the potential time you might have saved by protecting yourself against the designer messing up your code.
Hardly economical in terms of keystrokes and productivity but a possibility, if you're finding the event in code to 'Go To Definition' anyway, and imagining for a moment that you don't mind using the code editor features of VS, too, is to hit the Tab key, then add the += before hitting the Tab key another two times. This will generate the appropriate delegation and method definition, which will result in you seeing the method signature.
For instance, typing the following, tabbing appropriately (twice after typing '+='):
MyType.MyEvent += new System.EventHandler(MyType_MyEvent);
Generates a method like the following:
void MyType_MyEvent(object sender, EventArgs e)
{
throw new NotImplementedException();
}
Now, the productivity reduction could occur if you don't actually require both pieces of code.
I'm new to the Visual C# designer so these are general and pretty basic question on how to work with the designer.
When we for instance add a label to a form and then double-click on it in the Visual C# designer (I'm using Microsoft Visual C# 2008 Express Edition), the following things happen:
The designer generates code within Form1.Designer.cs (assume default names for simplicity) to add the label,
then with the double-click it will add the event handler label1_Click to the label within Form1.Designer.cs, using the following code
this.label1.Click += new System.EventHandler(this.label1_Click);
and it adds the event handler method to Form1.cs
private void label1_Click(object sender, EventArgs e)
{
}
If I now remove the label only the code within Form1.Designer.cs will be removed but the label1_Click method will stay within Form1.cs even if it isn't used by anything else. But if I'm using reset within Properties->Events for the Click-event from within the designer even the label1_Click method in Form1.cs will be removed.
1.) Isn't that a little inconsistent behavior?
2.) What is the recommended way of removing such generated event handler-code?
3.) What is the best "mental approach"/best practice for using the designer?
I would approach it by mental separation in the way that Form1.cs is 100% my responsibility and that on the other hand I'm not touching the code in Form1.Designer.cs at all. Does that make sense or not? Since sometimes the designer removes sth. from Form1.cs I'm not sure about this.
1) Yes, it is inconsistent. A little.
2) I used MUCH MORE SIMPLE approach: simple wipe out all your handle code and try to compile => compiler will show you where to wipe out an event assignment. Despite of scary look, it is really safe.
3) Here is my best practices which I recommend and kind of enforce in my software department:
3a) Switch to WPF (ask for best WPF practices separately; there are a lot of other problems);
3b) NEVER ever allow Visual Studio to auto-generate event code (WPF or Windows.Forms); in case of accident use (2) as soon as possible;
3b) For event assignment use anonymous lambda:
ByButton.Click += (source, evArg) => { SomeHandler(...); };
for v.2.0:
ByButton.Click += delegate(object source, EventArgs evArgs) { SomeHandler(...); };
There are many benefits: your handlers are not bound to using specific method profile; you can put whole code inside anonymous handler is it is short enough, in lambda form you may never need to know the type of Event Arguments...
There probably is a element of safety built into Visual Studio.
For example:
Add a button A and a click event.
Reference the button A click event from another button B.
Remove button A
if the code were to go then button B would break
if the code remains then button B continues to work.
I generally comment out any code (event handlers) that break in the designer.cs file.
Calling all Visual Studio gurus — when I'm working on a .ascx or .aspx file in a c# web project, the events do not show up in the properties panel unless I switch into the design view from the code view. Is this an intentional functionality of Visual Studio? Both VS2005 and VS2008 seem to work this way.
And is there any way to get the events to show up in the properties panel all the time?
I don't know if that's the way VS is 'intended to work, but yes that's a limitation. In case you've noticed sometimes clicking on the control and pressing F4 (or clicking on the properties tab) fails to load the properties for the correct control, and then you gotta select it from the list.
Sigh
That apart, if you make a usercontrol of your own, and give it an event, that event will not show up in the properties tab when you put it on a page. You'll have to capture it manually in the Page_Init event (like demonstrated by fallen888).
These days I don't bother with going to the properties tab to see an event. You can just as well type the event's name in the mark-up and then write it in the code-behind file.
Yes, that's how Visual Studio is intended to work. This doesn't help you view them in properties panel, but you can get a list of events (among other things) by typing the following in the code-behind:
"this." and intellisense should show you a list.
What I typically do is override the OnInit method and put all event handler mappings in there. So that it looks something like this:
override protected void OnInit(EventArgs e)
{
this.Load += new System.EventHandler(this.Page_Load);
this.myButton.Click += new System.EventHandler(this.myButton_Click);
base.OnInit(e);
}
If you do it using intellisense, as soon you type in "+= " you'll have the option to auto-complete that line and the event handler method's signature as well.
Yep, I wish we had a similar level of event autocompletion that we get with WPF where you can see the event name in IntelliSense and get it to automatically create a new stub event for you in code behind :(
I was just curious how others work with this kind of WinForm code in C#.
Lets say I have a Form lets call it Form1. And I have a DataGridView called dgvMain.
Where do you put the code:
this.dgvMain.CellEndEdit += new DataGridViewCellEventHandler(dgvMain_CellEndEdit);
Do you put it in the Form1 code or the Form1 designer code?
Should this "event wiring" code go in the Form1_Load method?
The reason I am ask is... if you double click the DataGridView the IDE inserts the code:
this.dgvMain.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dgvMain_CellContentClick);
into the designer code. Should your "event wiring" code be in two places?
Short answer is yes.
Longer answer is that .designer.cs is there for code generated by the designer. if you put your own code in there, it has a chance of getting overwritten, screwing up the design time stuff in visual studio, and lowers maintainability because nobody expects custom code to be in there.
This is a touchy subject. In 1.1, there where regions for this in your forms file, but a lot of the time, the code would be over written by the designer. I'm speaking from webforms experiance, but I would only gather that it would be the same elsewhere.
Now, you actually put the eventname in the form itself (it's one of the properties on the forms designer), and the code generator will push out the += event handler thingies in the partial class. I hate it this way, but it is what it is.
I use the Designer for all event related to Component.
I use the code for all object event.