Winforms App Not Displaying Graphical Elements in Design Mode - c#

I wrote a bunch of code in the .cs file in c# for a winforms application. The application runs fine, and everything is in it's place.
Something like this:
using..
namespace Temp
{
public class Temp : Form
{
Button b1;
TextBox t1;
Temp()
{
b1.Text = "Some Text";
b1.Size = new Size(50,20);
...
}
void function1()
{
// stuff
}
static void Main()
{
Application.Run(new Temp());
}
}
}
How can I modify my code (or fix it somehow) so that the design view displays the elements in their correct positions and view so that I can visually edit them instead of having to trial/error everything.
Edit for Clarification
My application runs fine. The problem is, that I didn't use designer to create the application and so in the designer view, the app is empty. But not empty when I run it, since everything is positioned programmatically in the .cs file. My question is, how can I fix this, so that the designer shows the objects correctly.
There is no quick fix other than to redesign everything?

So to get this shown within the designer you have to know how the designer works.
For every MyForm.cs there will automatically be a file called MyForm.Designer.cs be created. Within this Designer file there will be only one function called InitializeComponents(). This function will be called within the constructor of your MyForm.cs file.
The design viewer itself is responsible for the Designer file, so any change to this file while the design view is open would normally be discarded. Also if you put some code into the designer file that is not needed be the designer will be truncated.
So the next question is, when will this truncation happen? When you freshly open the design viewer of a form, it will read in everything from the Designer.cs file without making any changes. If you make any changes onto the form by the designer the complete file will be rewritten with all the settings already read in including your latest changes.
This behaviour can be monitored if you open the designer file also as source code view, make some little changes in design mode and afterwards take a close look at the left of the source file. There will be the changes marked with a yellow or a green marker.
Now after all this stuff of informations, you can try the following procedure to get your code into the designer:
Open the design view and put some simple control onto your form (e.g. TextBox)
Save and close the design view and open the Designer.cs file as source file
Copy all your variables name of your controls at the end of the file, right below the textBox1 line
Copy all your control property settings within the InitializeComponent() function right below the property settings of the TextBox
Copy all your control constructors to the top of the file, right below the constructor of the TextBox
Save the file and open your form in design view
Select the dummy TextBox on the design view and delete it
This change within the DesignView leads to a complete rewrite of the designer.cs file, ordering all your manually added stuff the right way.
So this is the way to go. Last but not least another little trick:
Every programmer uses the using-statement to not write the whole path to every class (like System.Windows.Forms.TextBox), but the designer writes always the whole path. To make it a little easier for your copy and paste session you can also add a using statement at the top of the file. After saving and changing something in Design View all this stuff will be re-written automatically. So you don't need to add all this paths manually while your adding your stuff to the Designer.cs file.

Your best option is probably to use the properties panel in the designer to set the positions etc (or maybe just drag them?).
You could go digging around in the designer file for the form (something.Designer.cs), but this isn't a fantastic idea because it can be pretty sensitive to changing things in ways the designer doesn't expect. Having said that, it looks like you're not actually using the designer to make your form (the class would be partial, for one thing), in which case you're SOL.

In that case, you need to copy the designer code from CS to designer.cs. So that you can use designer. I think this is the simplest approach.

Looks like this file was hacked from a class file instead of being generated by the system when you create a new winform.
You need at least an InitializeComponent(); call in your constructor. However you are missing a lot of other code that is generated for you when you create the file such as Dispose().
Best bet would be to right click your project in the solution explorer and click Add Windows Form then start over.

Related

Why does VS2017 keep losing my derived controls?

In my app namespace = DRT, I'm creating control classes (e.g., button, textbox) that derive fron their corresponding Windows control classes, e.g.,
internal abstract class DRT_Button_Abstract : Button
{
....
}
internal class DRT_Button_CancelSearch : DRT_Button_Abstract
{
....
}
internal class DRT_Button_StartSearch : DRT_Button_Abstract
{
....
}
All together I currently have 13 derived classes that derive either from one of my abstracts or from a Windows control class. After a successful build, I see my control classes (e.g., DRT_Button_CancelSearch and DRT_Button_StartSearch) on the Toolbox and I successfully drop them onto my main form. All is fine for a while, but ultimately, I'll go to open the main form.cs [Design] (i.e., the UI designer) and it will show the error The variable '{control property name}' is either undeclared or was never assigned. for some combination of my controls.
When I examine the main form Designer.cs file, the expected code for all the controls is present EXCEPT for the expected new statement. They are not present in the main form Designer.cs file. For example, I expect to see this.drt_Button_CancelSearch = new DRT.DRT_Button_CancelSearch(); but its missing
I've tried ignoring the error, proceeding to the UI designer windows to re-apply the lost controls, but the problem just repeats with the newly applied control
What the heck is going on? Is there a way to recover from this situation?
This is most likely a problem of the Designer not being able to clear/reload its cache. There is not much you can do. In the past I:
closed and reopened all designers that have user controls
put all the controls in a separate project (in the same solution)
put all the controls in a separate solution/Visual Studio instance and set a proper reference to the controls' dll (or even nuget package)
With the first two options I have had varying success. Reopening the designer is not very convenient and doesn't work.
That last option is the best but also the most annoying because every adjustment requires a rebuild of the project and update of the reference/package.
Also make sure that all controls that you create have public default constructors and function well when this constructor is used.

Events automatically detaching

When I attach a event on a control in my Windows Form I've got the problem that, after a few time, it detaches from it automatically. Let me explain, For example if I've got this line of code:
this.btnMainMove.MouseMove += btnMainMove_MouseMove;
And then I'll write the method btnMainMove_MouseMove in the form code, it works well for a few times but then in the designer file the line written above automatically deletes and I remain only with the method in the form code file.
This thing doesn't happen for the Click event but only for the methods that I create like MouseMove, MoseOver, KeyDown.
I'd like to know why this happens and how I could prevent this.
Thank you all!
Designer files are generally well marked with a message like so:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18034
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
The message is pretty clear. Changes can and will be lost.
These kinds of files, for instance, often have a tool that can be executed manually (using context menu options) but are most often executed automatically, after saving the accompanying *.cs files, compiling, etc.
Attach your events in the constructor, on load, or using the visual designer (which will track requirements based on layout files and other such things, but out of your concern).
I don't know what's the problem but i can suggest you use lambda expressions and not the designer
this.btnMainMove.MouseMove += (sender,event) =>
{
//your event logic here
};
but do this without clicking the event in the GUI of Visual Studio so you don't use the designer.
Are you editing *.designer.cs file manualy?
It is good to avoid it, but you can subscribe to this event in constructor, right after InitializeComponent() method.
The designer makes changes only in *.Designer.cs files...
If you add the Handlers in the Constructor or the Load-Event of the form the designer won't delete your code.

Controls on Form Not Shown in Designer

I am working on a WinForms project, and I have a form where I have a DataGrid, a TextBox, and 2 button controls (btnNew and btnSearch). The click event of a btnSearch is supposed to perform a search on the DataGrid.
I deleted the event handler for the search button and have saved my work. It now appears that all other controls have been deleted and the form is back to the default state. The application works fine though when run, with some errors. I have resolved the error but the designer view is still in the default state. How do I go about reinstating my form's design view?
i had your problem and solved it in this way:
just make another form with another name(NewForm.cs) and copy the InitializeComponent() content from YourFirstForm.designer.cs and paste it into
NewForm.designer.cs InitializeComponent() function. but be careful when copy and paste the function content change all YourFirstForm keywords to NewForm . finally Remove YourFirstForm and just work with your NewForm....
With the control selected in the properties window.
Right click on an empty space on the form,
Click cut
Right click / then paste into a cell somewhere in a form control.
I've run into errors like this before where simply closing all the form's files (code view + design view) re-open the code view and then Shift-F7 to reload the design view would fix it.
If that doesn't work perhaps fixing the error you mentioned in the designer view caused something to get out of whack. Try comparing the structure in the YourForm.Designer.cs file with a new form to see if an inadvertent edit was made.
i had your problem in Visual Studio 2017 and solved it in this way:
-select controls by Properties
-view Location is -
-change the Location
-drag the control to another location
Make sure all errors related to form are removed and your code compiles successfully.
If Form has been copied from an existing project make sure Form.Designer.cs and Form.resx are under same parent Form.cs and not separate. Check Form tree in Solution explorer. If they are not under the same tee, load the designer.cs and .resx file again in the project.

Prevent Visual Studio from updating specific lines in Form.Designer.cs

I was wondering is it possible to prevent Visual Studio from updating specific lines that are changed by me?
For example i have separate resource only project (images, sounds, etc). I change some lines in Form.Designer.cs and make so all images are loaded from resource dll. But once i update Form it self everything goes back to default and all resources that were used by form gets copied to Form.resx file.
How could i solve this?
Nope.
As stated in the begining of the file, the *.Designer.* is an auto generated file. It's rebuilt every time that the file it depends upon is saved, so you should never change any code there that you don't want to be messed.
It is preferable to separate the code that the form designer generates from the code that you want to have some control over. The order in which you need to address this code can then be handled within the constructor of the form. Example:
namespace FormTest
{
public partial class Form1 : Form
{
private Label PostAddedLabel;
public Form1()
{
InitializeComponent();
PostInitializeComponents();
}
private void PostInitializeComponents()
{
if (!this.DesignMode)
{
PostAddedLabel = new Label();
PostAddedLabel.Left = 100;
PostAddedLabel.Top = 30;
PostAddedLabel.Text = "The Post-added Label";
this.Controls.Add(PostAddedLabel);
}
}
}
}
We can simply design the form within the designer, after a successful design phase we then can MOVE the declaration, assignments and related code that we want to separate to the PostInitializeComponents method.
By using the !this.DesignMode decision, the form will show the separated controls in Runtime mode. When in designer-mode these controls will not be shown, assuring that the system will not affect these controls when designing the form.
In case you want to use this methodology also in usercontrols, try to embed the "IsDesignerHosted" method over "DesignMode" from the following article: DesignMode with Controls
Hope this answers the question?
No. Visual Studio does not "update" the Designer file, it deletes it and writes an all new copy. No possible way to do what you want.
You should add your code to your code behind. It's the same class.

Efficient Declaration/Creation of variables/controls

I'm working on cleaning up an app I'm almost finished with and I noticed something that made me curious as to why it's being done that way. While you can edit the .Designer.cs in your project for a form, there is a lot of autogenerated stuff in there, such as the creation of variables and controls. They have the Windows Form Designer generated code which hardly ever gets touched by me. But as I was making variables in the format I like them:
string strValue1,
strValue2;
As compared to:
string strValue1;
string strValue2;
I noticed that Windows declares the controls on the bottom of the file then creates/instantiates them in the InitializeComponent() function. Now, I knowI could take the "new" instances and put them where the declarations are and it seems to run fine. My question is what's the benefit of one over the other? Or is this the way it is so Windows can autogenerate them for us? If there's a possibility of better performance for doing it one way over another, I'd like to know. Thanks guys for the help.
Example 1:
private void InitializeComponent()
{
...
this.control1 = new System.Windows.Forms.Control();
...
}
...
System.Windows.Forms.Control control1;
Example 2:
private void InitializeComponent()
{
...
}
...
System.Windows.Forms.Control control1 = new System.Windows.Forms.Control();
Do not edit that code. It is auto-generated and the designer actually reads the code back to recreate the form in the designer. When you make changes like this, it is very likely you'll bomb the designer and your form becomes un-designable. Even if you do manage to avoid crashing it, your changes will simply disappear when you alter the form in the designer.
Anything in the region that's marked "Windows Forms Designer generated code" is hands-off.
There is no benefit whatsoever to changes like these. It generates the exact same code.
You can get some more control over stuff when its done in the InitializeComponent
If you open up your .cs file (not the designer) and look at the constructor
public Form1()
{
InitializeComponent();
}
this way you can have code execute before the controls are instantiated..
if you would just create the controls when they are declared then you would not be able to do this...

Categories