Can I stop Visual Studio auto-changing the form designer code? - c#

I'm using visual studio and have some numericUpDown controls that I have set values for (min, max, value and increment). The Code Designer keeps turning my simple decimal values into int[]. I know that it says "do not modify the contents of this method with the code editor" but I find it really useful to adjust properties in here and I thought I was just "making things neat" when I changed:
this.numericUpDown1.Increment = new decimal(new int[] {
2,
0,
0,
0});
to
this.numericUpDown1.Increment = new decimal(2);
but alas, it changes it back if I touch the control on the visual form designer. I thought maybe there was a flag that would leave it as is until I want it to be updated. It is more for readability and navigation but even if it would just leave it on one line I'd be happier.
I've found this (How can I tell Visual Studio to not populate a field in the designer code?) where someone was trying to leave it but I'm not sure if it is applicable in this instance.
Feel free to tell me that I should just get over it and leave it alone!

Just realised (thanks #Jonathan) that I could just create a separate section in the designer ABOVE that place ... this means I can have all my default values in a separate section as long as I don't want to changed the defaults on the form designer. This is the method above InitializeComponent()
private void IntializeOtherComponents()
{
this.numericUpDown1.Value = new decimal(17);
this.numericUpDown1.Maximum = new decimal(7777);
this.numericUpDown1.Minimum = new decimal(5);
}

You could make your own NumericUpDown user control. Just inherit from the common NumeriUpDown and set the dessired properties in the constructor.
public partial class MyUpDownCtrl : NumericUpDown
{
public MyUpDownCtrl()
{
InitializeComponent();
this.Increment = new decimal(2);
}
}
After generating your solution you will have your new custom UpDownControl in your Tool Box ready to use just dragging it like the common numericUpDown.
I hope it help you, because I don't know any way to make Visual Studio stop auto-changing the form designer code. Maybe it can't be done at all.

Related

How do I apply the Settings.settings values at design time?

I have a panel in my Form like this:
and a Panel_BackColor in project's Settings.setting file:
I can change panel back color in the Form constructor:
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
panel1.BackColor = UI_Settings.Default.Panel_BackColor;
}
}
All things work at runtime:
But nothing change at Design Time. How can I apply these settings at Design mode too?
I got your question, I try to handle with it when I use MetroFramework. Some changes just shown in runtime because it use another drawing technic with xml or .netframework when you use runtime code. So, I think you can't see changes in design time.
Next time try to explain a little more in details or maybe add some code or images to make us understand better.
In C# you have the property:
//Namespace: System.ComponentModel
//Gets a value that indicates whether the Component is currently in design mode.
//true if the Component is in design mode; otherwise, false.
protected bool DesignMode { get; }
I asked "not edited version" of this question on MSDN forum and got an answer within an hour.
Questions like Convert int to string? is a good questions but mine is not!
I think stackoverflow should keep a watch on it's editors and policy.
The answer:
Select your control in Form Designer (for example a button), go to Properties, (ApplicationSettings),(PropertyBinding), then bind BackColor or other property to Button_BackColor or other settings. Afterward by changing settings in Settings.settings file, all binded controls would be affected.

C# dynamic update of control created in a dll

I created a Control and compiled it into a DLL:
namespace TSControlLibrary
{
public partial class BaseMaskedTextBox : MaskedTextBox
{
public BaseMaskedTextBox()
{
InitializeComponent();
this.BackColor = Color.Pink;
}
}
}
Then I created another Test project and want to use this new MaskedTextBox on it...
Which pretty much works,
1 - I added the reference to the DLL in Test. And kept the default properties. Copy Local = True, Specific Version = False
2 - I added the DLL to the toolbox, which shows the BaseMaskedTextBox.
Now I can add a new masked thingy onto my winform. :-)
BUT!!! But when I want to change the original DLL from Color.Pink to Color.Blue it will allow me to add a new MaskedTextBox on the form in Blue. But the Pink is still Pink.
What I would like to do is change the DLL color, recompile that and the new Test project will have the new color. How can I do this?
VS2012, winforms, heh.
hmm... well, it looks like I figured it out. :-)
I found that the DLL color set works, it updates the color from the default to Green or whatever, but then the Test.Designer.cs runs after that and just resets it to whatever it was when I added it hours ago.
So after a while on my Test form I have 30 different boxes all different colors. Because the designer.cs keeps track of where they go and some other things - like colors and font size and things.
So, I found that LocationChanged event will fire after the designer, but before it shows on the screen. So that was the ticket.
public BaseMaskedTextBoxDate2()
{
this.LocationChanged += new EventHandler(Setup);
}
//*************************************************************************************************
private void Setup(object sender, EventArgs e)
{
MaskedTextBox maskedBox = (MaskedTextBox)sender;
maskedBox.BackColor = Color.Gray; // For testing and also to make sure all fields are handled.
maskedBox.Font = new Font("Microsoft Sans Serif", 10.0f);
maskedBox.ValidatingType = typeof(System.DateTime);
maskedBox.BeepOnError = false;
maskedBox.TypeValidationCompleted += new TypeValidationEventHandler(maskedTextBoxDate_TypeValidationCompleted);
...
}
Now, if I have the DLL version ( above ) open in an instance of VS and make a change, say to the font size, going from 10 to 20, on the other instance of VS that is Test it will update on the Test Design View instantly - and with 20 font it will also be pretty nasty looking... And when compiled it will also be correct - as shown in Design.
Oddly, the only thing that I can't change is the Mask. But I doubt I will ever change that from 00/00/0000 - at least for this project anyway.

c# How to link combobox SelectedIndex to ApplicationSettings

In Visual Studio designer (I use 2012) there is no way to link ApplicationSettings mechanism to SelectedIndex property (only Text).
What workaround can be used instead?
Sorry if my question was against StackOverflow rules. I searched for my question and found no exact answers.
I don't know only how to custom code ApplicationSettings. I always used this feature in design mode - linked Text properties of my textboxes and then used Properties.Settings.Default.Save() to save this and on Form_Load I used Properties.Settings.Default.SomeName to load saved values.
Everything besides this was done by VisualStudio and I don't know what exactly to change its behaviour for my needs.
I was sure that this question would be useful for starting programers
Write some code, it is as easy as using designer, besides, designer generates too much code which you don't understand.
Edit Settings in Visual Studio, add a property named "SelectedIndex", set its Type as int, and Scope as User, Value as 0 (meaning the 1st item is selected). And you can access this property in your code:
public Form1()
{
InitializeComponent();
comboxBox1.SelectedIndex = Properties.Settings.Default.SelectedIndex;
this.Closing += Form1_Closing;
}
void Form1_Closing(object sender, CancelEventArgs e)
{
Properties.Settings.Default.SelectedIndex = comboxBox1.SelectedIndex;
Properties.Settings.Default.Save();
}

Recreate a group of Controls

Let's say that I have a panel with like... 3 controls in it. I may end up adding more controls to it or changing the positioning within that panel. When the program starts, I will programmatically HIDE the control. Eventually, the user can click a button that will create a duplicate of the original panel to populate an area on the form. The button should have the option for another click eventually, meaning that multiple instances of these can come about to populate this area. Remember that these controls may have text labels within them that can be individually set or altered later on, programmatically. I am assuming that to do this program, I need to make a List of controls, maybe a List of panels? I'm not exactly sure how to do this considering the fact that I need multiple controls duplicated multiple times.
Is there a nice, simple way to do this? I really don't want to do the duplication with any kind of 3rd-party package.
You will have to do it in code and therefore it'll be as nice as you can code ;-)
Seriously the course most often taken is to
create a UserControl which is a class related to a form, with the layout you want..
..and add more and more instances of it..
..often to a FlowLayoutPanel, often with AutoScroll
This is pretty nice and simple imo.
Here is a short walk-though..:
first we start, as usual, by picking a nice name for the UserObject class, maybe 'DataPanel' or 'BookItem'..
Next we create it: Go to the project explorer and right-click, choosing Add-New UserControl and give it the class name you chose. I'll use 'BookItem'.
Now you can see the Designer showing you a small empty control.
Look closer: You can also see that in the project explorer ther is now not only the new 'BookItem.cs' file but also the complementary 'BookItem.Designer.cs' and even a 'BookItem.resx' file; so this works very much like creating a new Form..
Let's add a few controls from the toolbox, I chose to add a PictureBox, four Labels and a NumericUpDown.
Have a look at the BookItem.Designer.cs file: Here you can see the very things you see in a Form.Desginer.cs file: All settings and all declarations for all controls you add to the layout. Note especially the declarations (at the bottom of the file): Just like for a Form, all controls by default are declared as private!
We can now work on the layout and script the controls. We also can add functions and properties to the UC, just like a Form.
Please note: Anything you need to access from outside, read from your form or its methods must be public! So if you want to access the NUpDown, let call it 'nud_quantity' you have a choice
You can change its declaration in the BookItem.Designer.cs from private to public or in the Designer by changing the Modifiers property
Or you can write a public function in the UC to get/set its value
Chosing between those two ways is a matter of taste; if other developers will work with the UC class, it will probably be better to put close control over what you expose by writing access methods.
After you have compiled the project you can see the new UC in the Toolbox.
You can now either add it from the Toolbox or
you can add it in code like any control you create dynamically.
Let's look at an example:
Imagine a simple order system in a bookstore: The customer has done a search on the books in our store and is presented with a list of books in a DataGridView 'dgv_bookList', readonly, multiselect. To the right there is a FlowLayoutPanel 'flp_cart' represeting a shopping cart. And we have a command button 'cb_addItems' to add selected books to the cart.
The Button might be scripted like this:
private void cb_addItems_Click(object sender, EventArgs e)
{
if (dgv_bookList.SelectedRows.Count <= 0) return;
foreach (DataGridViewRow row in dgv_bookList.SelectedRows)
{
BookItem book = new BookItem (row);
book.label1.Text = "#00" + book.label1.Text;
book.Name = book.label1.Text;
flp_cart.Controls.Add(book);
}
}
This will add one BookItem for each selected row in the DGV.
A few things to note on the above code:
I pass a DataGridViewRow into the constructor of the UC so it can directly set its labels! This means that, in addition to the parameterless contructor the desginer has built for us, we need to write a second contructor, maybe like this:
public bookItem()
{
InitializeComponent();
}
public bookItem(DataGridViewRow bookData)
{
InitializeComponent();
label1.Text = bookData.Cells[0].FormattedValue.ToString();
label2.Text = bookData.Cells[1].FormattedValue.ToString();
label3.Text = bookData.Cells[2].FormattedValue.ToString();
label4.Text = bookData.Cells[3].FormattedValue.ToString();
}
Instead you could write a public setData(DataGridViewRow bookData) function.
Also note how stupid my labels are named! You can do better than that, I hope!
Also note how I access 'label1' and modify its Text from a Button in the Form; to do that I had to change its declaration in the Desginer.cs file:
private System.Windows.Forms.PictureBox pb_cover;
public System.Windows.Forms.Label label1; // <<----expose this label !
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.NumericUpDown numericUpDown1;
Often preferrable: An access function, maybe like this:
public int quantity() { return (int) numericUpDown1.Value; }
Or, of course a Property:
public int quantity { get { return (int)numericUpDown1.Value; } }
Also note, that I set the Name of the BookData item to some variant of the 1st data item, my book id. This might as well, or better, happen in the constructor; and there should be a check to prevent adding the same item twice..
All in all one can say, that using UserControls is very much like working with Forms, including all the usual ways or tricks for inter-form communication: keep references, expose members, create properties and functions..
One final Note: Like with forms or subclassed controls there is one catch: By placing them in the designer, you assign the designer the responsiblity to display your UC during design time.
This is normally just fine; however it is also possible to introduce subtle mistakes which make it impossible for the designer to display the control. You need to correct these problems before the designer will be able to show a control or any form that contains it. Let have a look at a simple example of such a problem:
Let's script the Paint event of the PictureBox 'pb_cover' in the UC:
public Brush myBrush = null;
private void pb_cover_Paint(object sender, PaintEventArgs e)
{
if (pb_cover.Image == null)
{
Size s = pb_cover.ClientSize;
e.Graphics.FillRectangle(myBrush, 0, 0, s.Width, s.Height);
e.Graphics.DrawLine(Pens.Red, 0, 0, s.Width, s.Height);
e.Graphics.DrawLine(Pens.Red, s.Height, 0, 0, s.Width);
}
}
And let's modify the code in the Add button:
BookItem book = new BookItem (row);
book.label1.Text = "#00" + book.label1.Text;
book.myBrush = Brushes.OliveDrab;
flp_cart.Controls.Add(book);
Now, if you run the program all will be fine. Even if you try to look at the UC in the designer there may or may not be problems. But once you try to open a Form on which the UC was placed, the Desginer will crash and tell you that it can't work, since the Brush is null. Here the remedy is simple: add a default value to the Brush declaration and all is well. Other situations may need a little more thinking..
I don't even run into the problem btw, since I have not placed an instance of BookItem on the Form; they are only created in the Add Button..
I hope that gets you started!

Visual Studio 2008 Form Designer messes up boolean properties values

I have a very annoying problem I'm trying to solve for couple of weeks. I have a WinForms C# project where I developed my custom control (ListView + ToolStrip with ToolStripButtons). This control is used in different forms inside solution - but in other projects. For different forms I need to make certain buttons visible or hidden, so I have added to my control corresponding properties like
public Boolean DeleteButtonVisible
{
get
{
return tsbDelete.Visible;
}
set
{
tsbDelete.Visible = value;
}
}
Some buttons are visible by default, some are hidden. In designer when editing a form with my control I'm able to change those properties, buttons on control become visible or hidden as they should. But every time I'm changing anything in my control source file in all forms those properties are reset to default values regardless of what I have set in designer and I have to restore those values manually. Well, I'm using a source control so this is not that hard, but performing "Undo" on a couple dozen of files every time I change a bit in another file is a damn disaster.
I have tried to use [DesignerSerializationVisibility] attribute to fix this issue. If I used it with value "Hidden" it didn't do any good at all - values were just not saved. "Content" made buttons randomly disappear even if by default they were visible. "Visible" lead to no effect, as this is default value...
I don't want to set every button visibility for every form in my code - this is just not the way it should be done.
Does anyone know something about this?
Yes, the Control.Visible property is special. The getter does not return the last assigned value, it only returns true when the control is actually visible. That can have side-effects, you've found one. In this case probably induced when the control switches out of design mode. To do this correctly, you must store the assigned state in a backing variable. Like this:
private bool tsbDeleteVisible;
public bool DeleteButtonVisible {
get { return tsbDeleteVisible; }
set { tsbDelete.Visible = tsbDeleteVisible = value; }
}
Be sure to initialize the default value of the backing variable to the default value of tsbDelete.Visible. Use the constructor to be sure.

Categories

Resources