Object not loading when I add `Load_Event` - c#

The object I'm using is <asp:Chart/>. I built it using Visual Web Developper 2010's binding tool:
I changed the look and behavior with the properties pannel and a CSS sheet. Everything was coming out fine until I accidently double-clicked on the chart. This added a myChart_Load method to my code. Now if I boot my page with the empty chart load method, my chart disappears from the screen as if it was only looking in the chart_load to see what to do, see nothing then don't show anything, forgetting the binding tool and properties/CSS.
Then if I delete
protected void myChart_Load(object sender, EventArgs e) {
}
the empty load above, the compiler crashes and says it is expecting a load method. Any idea why it's behaving like this?

I don't know about why adding a Load handler it doesn't come back, but it's erroring now because in the markup, it added the event handler reference there OnLoad="myChart_Load", so it looks for this, can't find it, and throws an exception.

you can remove the method from code behind by just deleting it. you'll also have to remove the reference of the method found in the .designer.cs file.

Related

changing my windows form design removes some unrelated code

I'm having a strange issue that maybe being caused by my ignorance.
I have a treeview with an .AfterSelect and any time that i change the design of my form (in the deign view) the code gets removed for some reason.
here is my code
this.lstTreeView.AfterSelect += LstTreeView_AfterSelect; < this is the code that gets removed
this.lstTreeView.Location = new System.Drawing.Point(194, 56);
this.lstTreeView.Name = "lstTreeView";
this.lstTreeView.Size = new System.Drawing.Size(220, 498);
this.lstTreeView.TabIndex = 6;
this is the code that it allows to work.
private void LstTreeView_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
TreeNode CurrentNode = e.Node;
string fullpath = CurrentNode.FullPath;
MessageBox.Show(fullpath);
NrDirSearch(fullpath);
}
if anyone can give me some advice on why the .AfterSelect is being removed that would be really helpful.
I suggest you:
in the windows form designer, click the tree view to select it
in the properties grid click the lightning bolt and scroll to find the AfterSelect event
right click the name AfterSelect and choose reset
hit save all
Close out of the soution entirely/shut down visual studio
restart/reload the solution
Go back to the AfterSelect event as above, the box for which should be empty
click the drop down and choose your existing event handler
save all, quit and restart vs and check that the setting stayed
If you're finding it didn't stick, check that you don't have your designer open in another program e.g. A text editor that keeps autosaving an old version of the file that lacks the event handler?
Incidentally, the above process is how you add event in Design view - click the relevant control, lightning bolt, scroll to event wanted, double click the name of the event and you will be transported to your own code behind with a new named eventhandler created and ready to be filled
If you don't write any code in it, and go back to the designer and Reset the event as per the bulleted list instructions then your event handler method in your code will disappear. If you write code into the event handler then it is not removed when doing a reset, only empty handler methods are removed during reset
Side note: be careful with Undo if you see a message saying something like "performing this undo will cause a loss of work elsewhere" it usually indicates that the windows form design or designer.cs code will change as a result of actioning the undo
Designer files are safe to edit manually and it's sometimes necessary if the contents have gotten into a state where they are crashing the designer. I most often encounter this when deleting event handler s from my code that are still referenced in the designer. A screen appears saying a problem is preventing the forms designer from appearing, indicating the error line in the designer file. I have additionally in the past edited the designer directly to set large numbers of properties without the faff of using the designer - be mindful not to have a windows forms designer open at the same time as editing the designer.ca file because the forms designer will probably overwrite your changes. So long as you keep in mind that opening the same file in any two different editors at the same time can lead to conflict and loss of work, and take steps to ensure that edits in one editor are reflected in another before proceeding with further edits in the other editor, you'll be fine :)
Edit: having said that paragraph above, Mickey D made me realise an important point I'd overlooked:
The designer.cs file is read by the forms designer and uses to build the contents of the form, buttons, properties etc. As such if you are going to edit the designer.cs in a text editor you should limit your edits to only those things the forms designer can make use of, understand, represent and preserve when it next writes the file. Adding a line to set a button to enabled is fine. Removing a line that is causing it to crash is also good. Putting 27 methods that implement your entire program's database access strategy in is not a good idea as it will not be heeded or used to build the form when the designer reads the file and hence lost when the designer writes the file. If you're unsure of the difference between what will and won't be preserved stick to removing or fixing existing lines only rather than adding new lines of code
You should never[1] modify *.designer.cs files. They are code generated. Any changes you make are subject to being overwritten.
Instead either use the WinForms GUI Forms Designer to visually setup event handlers or you can do so in code in your form’s code-behind .cs file.
There are plenty of resources on the Net on how to use the WinForms designer.
[1] see Caius Jard's comment below for an exception to the rule that I concur with

Visual Studio error when adding a library in the Form.Designer.cs

So basically I add this code to my Form1.Designer.cs:
this.comboBox1.Items.AddRange(Enumerable.Range(0, 30).Cast<object>().ToArray());
which requires adding using System.Linq; on top of namespace WindowsFormsApp. The program runs just fine, the only thing is that when I go back to the Form1.cs[Design] GUI part, Visual Studio returns me the following error: To prevent possible data loss before loading the designer, the following errors must be resolved.
I can ignore that and the program works just fine, but it kinda worry me. Is there maybe another way to add the using System.Linq; line without making VS get angry at you?
There is no reason to modify your designer generated code. Just put your line of code in your Forms constructor, after the line/region that is already there.
I suppose Visual Studio rewrites your file and removes the using. Try changing your code to
...System.Linq.Enumerable.Range(0, 30)...
That said. You shouldn't add code to the desinger file on any other place as in the default constructor (if present) after the call to InitializeComponent() or inside a protected virtual void Dispose(bool disposing) function (if present).
And even then you should move the constructor or dispose function to your form1.cs file.
If you want to add items to your combobox do this via the property grid and let visual studio take core about writing the designer file or do it in the appropriate event handler (I would suggest either load or shown event).
The InitializeComponent wouldn't be the right place for modifing controls, since the next time you open the form in the designer the items are added to the combobox and get serialized during save unless your write
public Form1()
{
InitializeComponent();
bool designMode = (LicenseManager.UsageMode == LicenseUsageMode.Designtime);
if(!designMode)
{
this.comboBox1.Items.AddRange(Enumerable.Range(0, 30).Cast<object>().ToArray());
}
}

C# Form Application: How to avoid deleting the unwanted events "manually" from InitializeComponent()?

This is a simple scenario:
I add an event to a control on the form by double clicking on its field (in Events part). But, then I decide that it was unnecessary and delete the automatically generated method. I'll run the program and it gives an error telling me that the event still exists in the InitializeComponent() and I must delete it from there.
So, is there anyway to avoid deleting the event "manually"? Is there anyway to fully delete it without leaving any trace (specially in InitializeComponent())?
Update: Also, another question arose:
When I delete the method from the code, the method name in the event field will disappear. So, if the InitializeComponent() is linked to these events, why isn't it updated with the empty event field?
You should use again the events grid and right click on the event you have inserted.
Select the Reset Menu option. This will remove the event handler assigned in the InitializeComponent and the code of the emtpy event in the code designer.
Note, that if you add code at the event, Visual Studio doesn't remove the new code.
The best way to do this is through the Properties grid in the Designer. You can click the Reset button or just delete the text and it will remove the event hook-up in the InitializeComponent() method. If your method is empty in your code behind, it will also delete it there:
It makes sense that you would have to manually delete the method body if it contains code in case it accidentally got Reset in the designer or if your method is referenced from some other part of your code. Visual Studio is gong to err on the side of caution.
If you delete the method body first, the reason it is not deleting the references to it probably in part has to do with cutting-and-pasting code. If you wanted to move the method to a different place in your code, the acting of cutting it would sever the references to it. After you pasted it, then you would wonder why your event was no longer be called. Again, error on the side of caution since it's not that difficult for the developer to track down extraneous code.
This pertains to C# 2017. So hopefully it would help others.
I'm new to C# (or at least back to code it) and ran with the same issue.
I commented out the event that I did by mistake. Then in the Error list, you will find an error there because that event is missing. Double click on it. It'll take you to the Designer code that "wires" the event. Once there, find the unwanted event and comment it out/delete it. Take care!
Look at the properties window when you select the Control. Click on the little flash and you'll see the Events listed, along with your event (Click or whatever), and your event will have the name of the assigned method behind it. Just delete that method.
That deletes the method, only if it's empty and otherwise unused though, which is quite reasonable. After all you might have put a lot of work into that event handler. (note: Just tried it again and apparently it doesn't always delete empty methods even though it did a few minutes ago. weird.)
In the designer you go to the events tab for the control in question, select the event that has the unwanted handler; and delete the name of the handler. Then save the form again.
This doesn't delete the method itself I think, (possibly unless it's empty or just been added).
Update
I dare say the reason for why it nearly always doesn't delete the method is because it could be used as a handler on another control's event. After all, in the UI you only asked to remove one event's handler; not every handler bound to that method. Then there's the question of whether the back-end code is dirty (i.e. unsaved) - checking whether the method is empty or not isn't reliable in that case. Yes, all of these could be worked around, but having to delete the method manually isn't exactly a hardship :) and at least this way VS doesn't end up deleting methods you actually want to keep.
Go back to the form and hit CTRL+Z.

Prevent Designer from removing Attributes on Control members

I want to mark certain controls on my Windows Form with Attributes. So I added the Attribute in my TestAttributes.Designer.cs:
[AmbientValue(true)]
private System.Windows.Forms.Label label1;
But whenever I change the Modifiers-property of label1 using the properties-window of the designer, the Designer silently removes my Attribute from the declaration:
public System.Windows.Forms.Label label1;
I tried putting the declaration in the TestAttributes.cs to not mess with the .Designer.cs file. But when changing the Modifiers property the declaration is moved back to TestAttributes.Designer.cs and the Attribute is gone.
How can I prevent the Designer from removing my Attributes?
EDIT:
The question should better be: Can I permanently move the declaration of a control out of the *.Designer.cs file, so I can apply an Attribute there? As I wrote above, it gets moved back in some cases.
Thank you!
richn
If you want to keep designer support, I recommend using an external class library.
namespace ClassLibrary1
{
[System.ComponentModel.AmbientValue(true)]
public class TestClass : System.Windows.Forms.Label
{
}
}
You can compile something like this to a class library, and then import it to visual studio. If you don't know how to do that, follow the instructions below.
Right click the toolbox
Click "Choose Items"
Wait. Do not make the mistake of terminating visual studio now.
Select Browse.
Select your dll file.
I normally don't like people who give the "don't do it" answer, but don't do it.
Changing the designer class is dangerous, and can almost always lead to unexpected consequences. The designer code is reserved for the compiler, and it should always look like the compiler expects it to look.
If you really wanted attributes in what would otherwise be your designer code, you should instead make an empty application, and do the forms code yourself. You shouldn't be trying to modify designer code anyway, if you don't understand how to do it from scratch
If that seems like a lot of work, you can always try to use the designer as a model, and then copy that over to a new, non-windows forms project.
Untill recently i was lead to believe that designer was just part of the code and it was not to be touched. I was wrong. Turns out you can rip the entire thing out and then compiler will throw an error at you. Okay, that's fine, just define your own stuff, completely thus eliminating the necessity for a designer. here is how. Say you have a tag
<div id="div1" runat="server">
and you want to make it invisible on the back side without any designer.cs file present (we deleted it). First reference it along with other declarations (i.e. outside of page_load, somewhere on the outside)
protected System.Web.UI.HtmlControls.HtmlGenericControl div1;
Remember however, you MUST reference EVERYTHING that you use on the front side that has a runat="server" tag. So say you have a page with only a runat="server" label, on the back we reference to it as
namespace yournamespace.something
{
public class yourpagetitle: System.Web.UI.Page
{
protected System.Web.UI.WebControls.Image imgLogo;
protected System.Web.UI.WebControls.TextBox tbDate;
protected System.Web.UI.WebControls.Label yourLabelName;
Notice I added image and a textbox as additional examples. And huzza! You have thus completely eliminated the need for designer.cs file. Oh, and do notice, designer.cs file is nothing more than what we just did above, but it does it for you automatically. ...most of the time... When it fails, time to handle things your own way. I'm sure if you reformat your computer, reinstall everything, etc etc etc things will work again, no doubt. This is just a legitimate work around for those who do not have time to babysit and troubleshoot every little hick-up Microsoft does.

ASP.Net Exception within View Control

I admit, I'm an .NET n00b. Basically what I'm trying to do is I have a page with a text box on it and an image button. On click of the image button I want it to show a view control I have set up. Inside this view control is an image and some text. So this is what I have in my code-behind.
protected void btnSubmit_Click(object sender, ImageClickEventArgs e)
{
string email = txtUnsubscribe.Text;
vwSuccess.Visible = true;
}
Simple right? Well when I click on the button for submit, I get the "Object reference not set to an instance of an object." error message. Where am I going wrong?
Are txtUnsubscribe and vwSuccess both not null? Have you tried stepping through it in a debugger?
Based on the information (which is to say, based on not much), I'd guess you have an issue with the execution order.
Since you have txtUnsubscribe and vwSuccess members, I'm assuming you initialize these somewhere. If they are auto-generated from the aspx templates, then they are initialized automatically before the event handling so that method will never throw a null reference exception.
If the null reference exception is thrown by that event handler, then it must mean that one of these variables is not initialized (which means that at least one of them is not autogenerated from the aspx and instead should be initialized manually). If you are initializing the variables, then you are likely doing it too late in an event like PreRender or Render.
When you click the button in the browser the browser performs a PostBack to the web server. By default at this point the web server re-constructs the page, performs the event handling and then renders it back to the client. It is important to realize that the page isn't maintained on the server between requests.
The order of events during page load/postback can be found from MSDN: http://msdn.microsoft.com/en-us/library/aa719775(VS.71).aspx
Of course if the exception isn't thrown by that event handler, this whole answer is likely to be wrong and there's probably some simpler issue.

Categories

Resources