I am trying to add several controls like Labels, pictureboxes etc. to a Panel in c# Windows Forms. My code looks like this:
this.panel1.Controls.Add(this.label1);
Every time I put this in the panel1 section in my Designer.cs, it gets deleted after I switch between classes and forms. I am doing this so that I can "transform" the Panel into a Bitmap with all the other controls in it.
Well, as you can see, you are trying to modify code within
#region Windows Form Designer generated code
...
// Designer is supposed to put (or/and remove) any code within this region
// Do not put any custom code here manually
this.panel1.Controls.Add(this.label1);
...
#endregion
and you have a conflict with Designer. Just let it generate its code in the area which specially designed (and marked out) for that; put yours into, say, constructor:
public MyForm() {
// Let .Net initialize the form, create all constrols etc. first
InitializeComponent();
// Then, run your code here
this.panel1.Controls.Add(this.label1);
}
Try :
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.panel1.Controls.Add(this.label1);
}
}
Related
When creating a new UserControl in UWP the following code behind xaml.cs file is generated.
public sealed partial class MyUserControl: UserControl
{
public MyUserControl()
{
this.InitializeComponent();
}
}
I would like to update this file so we can have better logging when things like the xaml fails to parse correctly.
public sealed partial class MyUserControl: UserControl
{
public MyUserControl()
{
try
{
this.InitializeComponent();
}
catch (Exception e)
{
//do all the logging
}
}
}
Whether this is done by extending UserControl or just doing the above (or some other option), I would like to avoid having to do this manually for all future user controls that are created. Is there any way that I can update/extend the code that is generated when we create a new user control / xaml.cs file so that I don't have to manually add the extra logging each time?
Thanks.
No you can't.
UserControl is part of the uwp SDK and you can not edit that class itself. However you can create a child from usercontrol, within its constructor call constructor of its parent ( base ). Then you can create child of this new class to create your user controls and then work on wiring it up to the UI part as well which can be more complicated. So the simplest way to error log your xaml parsing right now is the way you are already doing it. You have to put that try catch. You can just create a snippet and every time you create a new user control just use that snippet on its constructor maybe that can save you some time.
I have a project that has forms that inherit properties from a base form (called frmBase). I have run into an issue that is really confusing me:
I want the program to center on the user screen, so I added
this.CenterToScreen();
to frmBase_Load(). That works great when I run the app, BUT, when I try to design any of the forms that inherit from frmBase, they all get moved to the very bottom right corner of the designer screen and I have to use scrollbars to see them.
If I move the
this.CenterToScreen();
to the frmBase() code, the app defaults to the top-left of the screen when it runs, but the designer displays the form correctly for me. Any idea what is going on? I searched, but can't seem to find a similar question, although I know I can't be the first person this has happened to. . . . .
As indicated by Hans and Reza your base class is being instantiated by the Visual Studio Form Designer so the code in the constructor and its Load event run as well. See this great answer for a detailed explanation of the parse behavior of the designer. Using the property DesignMode you can either prevent code being executed or make a distinction. The following code sample demonstrates its use:
Base form
The baseform sets the background color to Red when in DesignMode and Green when not in DesignMode.
// Form1 inherits from this class
public class MyBase : Form
{
public MyBase()
{
// hookup load event
this.Load += (s, e) =>
{
// check in which state we are
if (this.DesignMode)
{
this.BackColor = Color.Red;
}
else
{
this.BackColor = Color.Green;
}
};
}
}
Form1 that inherits the base form
No magic in the code, but notice the use of MyBase instead of Form
// we inherit from MyBase!
public partial class Form1 : MyBase
{
public Form1()
{
InitializeComponent();
}
}
Leading to the following result:
I am attempting to make a complete custom TabControl.
So far my code works perfectly, however when I'm viewing my TabControl in the Visual Studio designer, I cannot add Controls into the TabPage Control which is inside of the TabControl. When attempted, it just places the control on top of the TabControl.
Unless you are adding controls to the TabPage via programming it by hand, that is, not using Visual Studio's Designer, using the TabControl is pointless.
PasteBin Link to my Control's Code
Here are images of the tab control with different tabs selected:
(source: gyazo.com)
(source: gyazo.com)
As you can see from the above images, the button is not placed into the tab page's control collection, as it floats above the tab control.
You can Use Tabcontrol from Design Toolbox in form and place the controls as you want.Then add the piece of code provided below to your code this will work.
Suppose you have custom class as Use this code write the Constructor as given below.
internal class MyCustomTabControl
{
public MyCustomTabControl(TabControl tabControlPassed)
: base()
{
this.tabcontrol = tabControlPassed;
}
TabControl tabcontrol;
}
In the main form Initialization call MyCustomTabControl initialization after InitializeComponent() method. Pass the this.tabControl1 while initializing Custom tabcontrol.
public partial class TabForm : Form
{
public TabForm()
{
InitializeComponent();
MyCustomTabControl customTab = new MyCustomTabControl(this.tabControl1);
}
}
:)
I have a windows form and i dont want to make any other windows forms just one windows form and different user controls how can i change between user controls for example hide one and show the other user control programmatically ?
private void Btt_info_Click(object sender, EventArgs e)
{
Frm_Main frm_main = new Frm_Main();
frm_main.Controls["panel1"].Controls.Clear();
UC_Info uc_info = new UC_Info();
frm_main.Controls["panel1"].Controls.Add(uc_info);
}
i added this but it doesnt work
Add a container control (if I remember correctly, there's a containers section in the toolbox?), like a panel. Create usercontrols for what you want to dynamically switch around. So make like a 'HomePage' usercontrol and a 'LoginPage' usercontrol. Dynamically add the usercontrol that you want to display to the container. WHen you want, remove it from the container and add a different usercontrol:
Panel myPanel = new Panel();
LoginPage ctlLoginPage = new LoginPage();
HomePage ctlHomePage = new HomePage();
//add the loginpage to the panel first
myPanel.Controls.Add(ctlLoginPage);
...do stuff...
//remove whatever control is currently in the Panel
myPanel.Controls.Clear();
//add the other control, the HomePage control instead now
myPanel.Controls.Add(ctlHomePage);
..do other stuff...
I usually do it this way so you leave your form itself open to add common controls and stuff that might be shared between your different 'pages'.
EDIT: Note that I normally would add the panel in the designer and not create it dynamically in the code. This was just an example.
EDIT: The interaction between your mainform and usercontrols can be handled in a few different ways, and I am not saying that any of these is the correct method.
You create a static property for your Panel on the Mainform, so that
you can always access it to swap your controls around.
In this example I'll also add a static method for it
enum PanelControlsEnum {HomePage, LoginPage};
public static Panel MyContainerPanel {get;set;}
public static void SwitchPanelControls(PanelControlsEnum selControl){
..put your switch panels code here..
}
Then inside your usercontrol you call a predefined method, something like:
MainForm.SwitchPanelControls(PanelControlsEnum.HomePage);
Another method is to bind the button click event on your mainform
instead of inside the form.
Like This:
HomePage ctlHomePage = new HomePage();
ctlHomePage.Click += MyClickEvent;
myPanel.Controls.Add(ctlHomePage)
...
private void MyClickEvent(object sender, RoutedEventArgs e)
{
..switch user control code here...
}
Create a method that returns a UserControl object. Then put conditions in that method as to which control you want to load at a specific condition and then in your main form code.
UserControl control = GetControlFromMyMethod();
form1.Controls.Add(control);
where 'control' is the returned control from your method.
To remove the existing one you have to loop through the form1.Controls and find out the control and call 'Remove'.
Update:
Mike C has a better idea of adding a panel and loading your desired control on the panel as then it's easy to remove your control and you then don't have to loop through the forms controls to find it and then remove it.
Try this:
this.Controls.Clear();
usercontrol load = new usercontrol ();
this.Controls.Add(load);
load.Show();
you could try this it will definitely help you as it did helped me a lot it short and straight to the point hope that will help
I'm rewriting an old application and use this as a good opportunity to try out C# and .NET development (I usually do a lot of plug-in stuff in C).
The application is basically a timer collecting data. It has a start view with a button to start the measurement. During the measurement the app has five different views depending on what information the user wants to see.
What is the best practice to switch between the views?
From start to running?
Between the running views?
Ideas:
Use one form and hide and show controls
Use one start form and then a form with a TabControl
Use six separate forms
Creating a bunch of overlaid panels is a design-time nightmare.
I would suggest using a tab control with each "view" on a separate tab, and then picking the correct tab at runtime. You can avoid showing the tab headers by putting something like this in your form's Load event:
tabControl1.Top = tabControl1.Top - tabControl1.ItemSize.Height;
tabControl1.Height = tabControl1.Height + tabControl1.ItemSize.Height;
tabControl1.Region = new Region(new RectangleF(tabPage1.Left, tabPage1.Top, tabPage1.Width, tabPage1.Height + tabControl1.ItemSize.Height));
What I do is to have a Panel where your different views will sit on the main form.
then create user controls for your different views.
Then when I want to switch between a'view' you dock it to Panel on the main form.. code looks a little like this.
i preffer this because you can then reuse your views, like if you want to open up a view in a tab you can dock your user controls inside tab pages.. or even inherit from
tabpage instead of usercontrol to make things a bit more generic
public partial class MainForm : Form
{
public enum FormViews
{
A, B
}
private MyViewA viewA; //user control with view a on it
private MyViewB viewB; //user control with view b on it
private FormViews _formView;
public FormViews FormView
{
get
{
return _formView;
}
set
{
_formView = value;
OnFormViewChanged(_formView);
}
}
protected virtual void OnFormViewChanged(FormViews view)
{
//contentPanel is just a System.Windows.Forms.Panel docked to fill the form
switch (view)
{
case FormViews.A:
if (viewA != null) viewA = new MyViewA();
//extension method, you could use a static function.
this.contentPanel.DockControl(viewA);
break;
case FormViews.B:
if (viewB != null) viewB = new MyViewB();
this.contentPanel.DockControl(viewB);
break;
}
}
public MainForm()
{
InitializeComponent();
FormView = FormViews.A; //simply change views like this
}
}
public static class PanelExtensions
{
public static void DockControl(this Panel thisControl, Control controlToDock)
{
thisControl.Controls.Clear();
thisControl.Controls.Add(controlToDock);
controlToDock.Dock = DockStyle.Fill;
}
}
Tabbed forms are usually good... but only if you want the user to be able to see any view at any time... and it sounds like you might not.
Separate forms definitely works, but you need to make sure that the switch is seemless...if you make sure the new form appears the same exact size and location of the old form, it will look like it thew same for with changing controls.
The method I often use is actually to pre-setup all my controls on individual "Panel" controls and then show and hide these panels as I need them. The "Panel" control is basically a control container... you can move the panel and all controls on it move relative. And if you show or hide the panel, the controls on it do the same. They are great for situations like this.
The method I often use is actually to
pre-setup all my controls on
individual "Panel" controls and then
show and hide these panels as I need
them.
Instead of making each view a panel within a single form you could make each view a UserControl. Then create a single form and write code to create and display the correct UserControl in the Form and to switch from one to the next. This would be easier to maintain because you will have a separate class for each view instead of a single Form class with 6 panels each with their own controls -- that seems difficult and error prone to maintain.
I would also check out Composite Application Guidance for WPF or Smart Client Software Factory