How can i remove the tabs from tabcontrol using c# - c#

How can i remove the tabs from tabcontrol when i reference each tab to the childform.
I am using a tabcontrol, i want to remove a particular tab from the control. The value i have to do this in a string which i dynamically.
How to remove the tab from tabcontrol using a existing tab name which i have in a string ??
I tried something like...
string tabToRemove = "tabPageName";
for (int i = 0; i < myTabControl.TabPages.Count; i++)
{
if (myTabControl.TabPages[i].Name.Equals(tabToRemove, StringComparison.OrdinalIgnoreCase))
{
myTabControl.TabPages.RemoveAt(i);
break;
}
}
But in the above code, the myTabControl.TabPages.Count is always zero.
Below is the code, to show i am creating the tabs. This is working perfectly.
public void TabIt(string strProcessName)
{
this.Show();
//Creating MDI child form and initialize its fields
MDIChild childForm = new MDIChild();
childForm.Text = strProcessName;
childForm.MdiParent = this;
//child Form will now hold a reference value to the tab control
childForm.TabCtrl = tabControl1;
//Add a Tabpage and enables it
TabPage tp = new TabPage();
tp.Parent = tabControl1;
tp.Text = childForm.Text;
tp.Show();
//child Form will now hold a reference value to a tabpage
childForm.TabPag = tp;
//Activate the MDI child form
childForm.Show();
childCount++;
//Activate the newly created Tabpage.
tabControl1.SelectedTab = tp;
tabControl1.ItemSize = new Size(200, 32);
tp.Height = tp.Parent.Height;
tp.Width = tp.Parent.Width;
}
public void GetTabNames()
{
foreach (string strProcessName in Global.TabProcessNames)
{
TabIt(strProcessName);
}
}
The child form :
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Diagnostics;
using System.Drawing.Drawing2D;
namespace Daemon
{
/// <summary>
/// Summary description for MDIChild.
/// </summary>
///
public class MDIChild : System.Windows.Forms.Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private TabControl tabCtrl;
private TabPage tabPag;
public MDIChild()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//MDIChild TargerForm = new MDIChild();
//WinApi.SetWinFullScreen(TargerForm.Handle);
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
public TabPage TabPag
{
get
{
return tabPag;
}
set
{
tabPag = value;
}
}
public TabControl TabCtrl
{
set
{
tabCtrl = value;
}
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.SuspendLayout();
//
// MDIChild
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.BackColor = System.Drawing.SystemColors.InactiveCaptionText;
this.ClientSize = new System.Drawing.Size(0, 0);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "MDIChild";
this.Opacity = 0;
this.ShowIcon = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.Text = "MDIChild";
this.Activated += new System.EventHandler(this.MDIChild_Activated);
this.Closing += new System.ComponentModel.CancelEventHandler(this.MDIChild_Closing);
this.ResumeLayout(false);
}
#endregion
private void MDIChild_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
try
{
//Destroy the corresponding Tabpage when closing MDI child form
this.tabPag.Dispose();
//If no Tabpage left
if (!tabCtrl.HasChildren)
{
tabCtrl.Visible = false;
}
}
catch (Exception ex)
{
}
}
private void MDIChild_Activated(object sender, System.EventArgs e)
{
try
{
//Activate the corresponding Tabpage
tabCtrl.SelectedTab = tabPag;
if (!tabCtrl.Visible)
{
tabCtrl.Visible = true;
}
Global.ExistingTabProcessNames.Add(tabPag.Text);
}
catch (Exception ex)
{
}
}
}
}

For starters you should be looping the other way around:
for (int i = myTabControl.TabPages.Count - 1; i >= 0 ; i--)
{
......
}
EDIT: Ignore me. I missed the break; and yes it should also be >= :(
My next theory is you are missing this line:
// add the page to the tab control
tabControl1.Controls.Add(tp);
PS: Why does copying code from SO not maintain the CRLFs. That is very annoying!

As jussij suggested, you need to do this:
tabControl1.Controls.Add(tp);
And you can more easily locate the tab like this:
var foundTab = (from System.Windows.Forms.TabPage tab in tabControl1.TabPages.Cast<TabPage>()
where tab.Name == "tabName"
select tab).First();

I dont know the purpose of your code, but if you will eventually re-add the tab, why not just hide it? Its easier and you dont have to worry about reverse loop logic and invalid arguments once the page is hidden and such. If you need to need a way to address all the tabs at once just do a check for visible tabs...

I would recommend taking a look at this tab page example for adding/removing tabs.

Related

Access a button from the form in other class in C#

I want to know if a button is pressed in C# from another class. I have my standard class Form and another class Device. Now I want to access the button from InitializeComponent in Form in my class Device. Does anyone know a good way to do this?
EDIT: If I press on the btnInitialise I want to show a messagebox (with text "test") to start with. I want to use this button in the class Device. I don't rely know how I can reference the button btnInitialise that is automatically made in my form to the class Device.
public class Form1 : System.Windows.Forms.Form
{
#region "Windows Form Designer generated code"
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.btnInitialise = new System.Windows.Forms.Button();
this.cmbdevice = new System.Windows.Forms.ComboBox();
this.tabControl1.SuspendLayout();
this.tabPage1.SuspendLayout();
this.SuspendLayout();
//
// tabControl1
//
this.tabControl1.Controls.Add(this.tabPage1);
this.tabControl1.Controls.Add(this.tabPage2);
this.tabControl1.Location = new System.Drawing.Point(42, 41);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(645, 414);
this.tabControl1.TabIndex = 0;
//
// tabPage1
//
this.tabPage1.Controls.Add(this.grpDevice);
this.tabPage1.Location = new System.Drawing.Point(4, 22);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Padding = new System.Windows.Forms.Padding(3);
this.tabPage1.Size = new System.Drawing.Size(637, 388);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "tabPage1";
this.tabPage1.UseVisualStyleBackColor = true;
//
// btnInitialise
//
this.btnInitialise.Location = new System.Drawing.Point(351, 16);
this.btnInitialise.Name = "btnInitialise";
this.btnInitialise.Size = new System.Drawing.Size(96, 25);
this.btnInitialise.TabIndex = 21;
this.btnInitialise.Text = "Initialize";
this.btnInitialise.Click += new System.EventHandler(this.btnInitialise_Click);
//
// Form1
//
this.ClientSize = new System.Drawing.Size(1005, 532);
this.Controls.Add(this.tabControl1);
this.Name = "Form1";
this.tabControl1.ResumeLayout(false);
this.tabPage1.ResumeLayout(false);
this.grpDevice.ResumeLayout(false);
this.grpDevice.PerformLayout();
this.ResumeLayout(false);
}
private TabControl tabControl1;
private TabPage tabPage1;
private Button btnInitialise;
#endregion "Windows Form Designer generated code"
#region "Global variables"
// OpenLayers fields
////Encapsulates a DT-open layers deviceand manages and distributes subsystems for the device
private Device device = null;
#endregion "Global variables"
//Automatically to initialize components of form
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//Set the culture to en-US for decimal point instead of decimal comma in results
CultureInfo english = new CultureInfo("en-US");
CultureInfo.DefaultThreadCurrentCulture = english;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (device != null)
{
device.Dispose();
}
}
base.Dispose(disposing);
}
/// <summary>
/// The main entry point for the application.
/// </summary>
///
//Run application, show error message if appl doesnt run
[STAThread]
private static void Main()
{
try
{
Application.Run(new Form1());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString(), "Error");
}
}
}
public class Device
{
//When clicking on the initialize button show messagebox
private void btnInitialise_Click(object sender, EventArgs e)
{
MessageBox.Show("test");
}
}
}
You have to expose the button to other classes. One way to do so would be using public property. e.g.
public Button MyButton
{
get { return button1; }
}
then from the Form class you can use it as
Device d = new Device();
Button b = d.MyButton;
Note: This example is based on what you have asked in the post. However, it is not clear what are you actually going to achieve by getting a button like this! If you add a code sample and more info about the application you are developing we can help you better.
Your Form constructor should look like this:
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//Set the culture to en-US for decimal point instead of decimal comma in results
CultureInfo english = new CultureInfo("en-US");
CultureInfo.DefaultThreadCurrentCulture = english;
device = new Device();
this.btnInitialise.Click += new System.EventHandler(device.btnInitialise_Click);
}
Now in Device you should make the eventhandler public, like this:
public class Device
{
//When clicking on the initialize button show messagebox
public void btnInitialise_Click(object sender, EventArgs e)
{
MessageBox.Show("test");
}
}
Now the Device's btnInitialise_Click method will be triggered when you click the button.
Edit: Fixed typo in Device, try Again.

Change Label.Text on it's own click event during Runtime?

All I need is a field that can be renamed by users as they wish by just clicking on it, I am using a label as the control here, when ever user click on it user could be able to enter text in the label and when he click outside of the label that enter text would be saved as the label text.
This is a quick solution:
private void label1_Click(object sender, EventArgs e)
{
TextBox tb = null;
if (label1.Controls.Count > 0) // do we already have created our TextBox?
{
tb = ((TextBox)label1.Controls[0]); // yes. set reference.
// is it already visible? we got clicked from outside, so we hide it:
if (tb.Visible) { label1.Text = tb.Text; tb.Hide(); return; };
}
else if (sender == null) return; // clicked from outside: do nothing
else // we need to create the textbox
{
tb = new TextBox();
tb.Parent = label1; // add it to the label's Controls collection
tb.Size = label1.Size; // size it
// set the event that ends editing when focus goes elsewhere:
tb.LostFocus += (ss, ee) => { label1.Text = tb.Text; tb.Hide(); };
}
tb.Text = label1.Text; // get current text
tb.Show(); // display the textbox in place
}
It embeds a TextBox into the Label. Style the Label to be big enough for the expected user entry!
It expects no other controls to be embedded there.
If you need it more than once consider creating a custom editable label from this code!
Note that to work you need to click at a spot where focus can go, not just the empty space around. To remedy that you could code the Click event for the surrounding space, maybe like this:
private void unClickLabel(object sender, EventArgs e) {label1_Click(null, null);}
In the form constructor add this to all the 'outside' controls that won't take focus, like the Form or a TabPage or a PicureBox or a Panel:
public Form1()
{
InitializeComponent();
this.Click += unClickLabel;
tabPage1.Click += unClickLabel;
pictureBox1.Click += unClickLabel;
..
}
Note that the new Label text will not persist program runs! To allow that you need to store it in some outside user settings and load them at startup..
You should create your own UserControl which contains one label and one textbox. Implement its functionality like you want.
I have created a sample usercontrol to give you an idea about it...
Update:
Follow these steps to use this custom control.
Right click on your project and click 'Add-> UserControl'
Name it 'EditableLabelControl' and click Add.
Go to 'EditableLabelControl.Designer.cs' and replace the partial class Code1 below.
Then go to 'EditableLabelControl.cs' and replace second partial class by Code2 below.
Build your solution.
You should be able to add EditableLabelControl to your form(it will be shown in toolbox)
Code1
partial class EditableLabelControl
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.textBox1 = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(0, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(35, 13);
this.label1.TabIndex = 0;
this.label1.Text = "label1";
this.label1.MouseClick += new System.Windows.Forms.MouseEventHandler(this.label1_MouseClick);
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(0, 0);
this.textBox1.Name = "textBox1";
this.textBox1.TabIndex = 1;
this.textBox1.Visible = false;
this.textBox1.Leave += new System.EventHandler(this.textBox1_Leave);
//
// EditableLabelControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoSize = true;
this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.Controls.Add(this.textBox1);
this.Controls.Add(this.label1);
this.Name = "EditableLabelControl";
this.Size = new System.Drawing.Size(103, 23);
this.ResumeLayout(false);
this.PerformLayout();
}
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox textBox1;
#endregion
}
Code2
public partial class EditableLabelControl : UserControl
{
public EditableLabelControl()
{
InitializeComponent();
}
private void label1_MouseClick(object sender, MouseEventArgs e)
{
textBox1.Visible = true;
textBox1.BringToFront();
textBox1.Focus();
}
private void textBox1_Leave(object sender, EventArgs e)
{
label1.Text = textBox1.Text;
textBox1.Visible = false;
textBox1.SendToBack();
}
}
Just add this EditableLabelControl to your form and it should work.
Try using TextBox instead of Label.
Use a TextBox control and set the ReadOnly property to true, if you would like to have a non-changeable text field. However, keep in mind, the TextBox will not resize automatically and does not support transparency.
You can change the property BackColor to Control and the BorderStyle to none, this will appear like a label.
With more effort you can create a UserControl and switch between the Lable and TextBox.
I recommend using textBox instead.
Replace the label with textBox.
//Set properties. Make the textBox looks like label
yourTextBox.BackColor = SystemColors.Control;
yourTextBox.BorderStyle = System.Windows.Forms.BorderStyle.None;
//Allow user to change text by double clicking it
yourTextBox.DoubleClick += new EventHandler(this.doubleClick);
//Do stuff when user double click it. Double click again to end editing.
public void doubleClick(object sender, EventArgs e)
{
TextBox temp = (TextBox)sender;
temp.ReadOnly = !temp.ReadOnly;
temp.DeselectAll();
if (temp.ReadOnly)
{
//Make the textbox lose focus
this.ActiveControl = null;
}
}

How to create an array of User Controls / indexing user controls in C# / Silverlight?

I am an old time user of the Array of controls in VB back in the days. It is gone now, so I am looking for a replacement.
I have created an User Control in C# for Silverlight. This control exposes a bool property IsChecked.
<ImageButton Name"imgbutton1" IsChecked="True"/>
<ImageButton Name"imgbutton2" IsChecked="False"/>
<ImageButton Name"imgbutton3" IsChecked="False"/>
In a Child Window, I populate a series of these controls and use them as an equivalent of RadioButtons, i.e., when I click one, any other that has an IsChecked = true will be set to false, for which I thought of doing something like:
List<ImageButton> imgButtons= new List<ImageButton>();
imgButtons.Add(imgbutton1);
imgButtons.Add(imgbutton2);
imgButtons.Add(imgbutton3);
Then, to clear all of their IsChecked but the one I need (pointed by some 'index' variable), I would do something like:
foreach (ImageButton imgbutton in imgButtons) imgbutton.IsChecked = false;
imgbuttons[index].IsChecked = true;
The problem I have is that List<ImageButton> is not compiling. I am very flaky at collections and can't figure out what I am missing. I can do for standard controls but doesn't allow me to get a user control in there.
Thanks!
PS: I have thought of just customizing a RadioButton control but don't have Blend and I am using this image control for other types of controls. However, if you think there is a better way to implement this, please let me know.
EDIT: Compiler says "The type or namespace name 'ImageButton' could not be found (are you missing a using directive or an assembly reference?)'
Ensure that you have a reference to your "ImageButton" control in your code (in the "using" part).
To do that automatically you can just rightclick on your "ImageButton" in your code and click "Resolve", it will automatically add the Reference
You didn't tell us what the compiler error was when you said "List is not compiling".
My guess is that you need to include the namespace of the List collection in your file.
using System.Collections.Generic;
Just thought of something else, I'm not sure why you are keeping a List<> of your ImageButtons if they are in the display (in that childwindow). If they are all within the same container your could use something like :
// here "grd" is your Grid container, it could be another type of container though
foreach (ImageButton imgBtn in grd.Children.OfType<ImageButton>())
imgBtn.IsChecked = false;
This may help.
The code for user control:
//usercontrol1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
namespace WindowsFormsApplication1
{
public partial class UserControl1 : UserControl
{
Color formcolor;
public UserControl1()
{
InitializeComponent();
}
public void setvals(string a1,string a2,string a3,string a4)
{
t1.Text=a1;
t2.Text=a2;
t3.Text=a3;
t4.Text=a4;
}
public Color formColor
{
get
{
return formcolor;
}
set
{
formcolor = value;
this.BackColor = formcolor;
}
}
}
}
usercontrol.designer.cs
namespace WindowsFormsApplication1
{
partial class UserControl1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.t1 = new System.Windows.Forms.TextBox();
this.t2 = new System.Windows.Forms.TextBox();
this.t3 = new System.Windows.Forms.TextBox();
this.t4 = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// t1
//
this.t1.Location = new System.Drawing.Point(20, 16);
this.t1.Name = "t1";
this.t1.Size = new System.Drawing.Size(100, 20);
this.t1.TabIndex = 0;
//
// t2
//
this.t2.Location = new System.Drawing.Point(20, 42);
this.t2.Name = "t2";
this.t2.Size = new System.Drawing.Size(100, 20);
this.t2.TabIndex = 1;
//
// t3
//
this.t3.Location = new System.Drawing.Point(20, 68);
this.t3.Name = "t3";
this.t3.Size = new System.Drawing.Size(100, 20);
this.t3.TabIndex = 2;
//
// t4
//
this.t4.Location = new System.Drawing.Point(20, 94);
this.t4.Name = "t4";
this.t4.Size = new System.Drawing.Size(100, 20);
this.t4.TabIndex = 3;
//
// UserControl1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.t4);
this.Controls.Add(this.t3);
this.Controls.Add(this.t2);
this.Controls.Add(this.t1);
this.Name = "UserControl1";
this.Size = new System.Drawing.Size(278, 133);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox t1;
private System.Windows.Forms.TextBox t2;
private System.Windows.Forms.TextBox t3;
private System.Windows.Forms.TextBox t4;
}
}
now in the form totally dynamically can create an array of that user control like this
A global variable
private UserControl1[] userControl11=new WindowsFormsApplication1.UserControl1[3];
and now the array of user control
you can write it on a button
this.SuspendLayout();
Random r=new Random(DateTime.Now.Millisecond);
for (int i = 0; i < 3; i++)
{
userControl11[i] = new UserControl1();
this.userControl11[i].formColor = Color.FromArgb(r.Next(255),r.Next(255),r.Next(255));
this.userControl11[i].Location = new System.Drawing.Point(133 , 133*(i+1));
this.userControl11[i].Name = "userControl11";
this.userControl11[i].Size = new System.Drawing.Size(278, 133);
this.userControl11[i].TabIndex = 0;
this.Controls.Add(this.userControl11[i]);
}
;

How to save a Control Array [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have this code that allow the user to create a button array, any were in a from.
Here and here are two samples of what I am doing (on Create an account now? Click NO and then download the zip file).
The problem or questions is as follow:
I need to save what ever the user makes: for example if he added 5 buttons and saved it, next time when he opens his saved file he will see the 5 button in the same place he save them.
This will allow the user to send the file to another person with the same program and the other person take a look at the created file.
Because of the misunderstanding (comments below) I will post some code with is the second link above. BUT the problem is that I cant find any code to do what I am asking. guys i do not have any idea on how to even start, I mean I know how to save a image from a picture box or some text but the button array is another thing.
Here is the code Simple example code or you can download the second file posted by me and compile it.
ButtomArray.cs
using System;
using System.Collections;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace ManageControls
{
public delegate void SendSelectedButton(object sender);
public class ButtonArray : Hashtable
{
private readonly Form HostForm;
public event SendSelectedButton SelectedButton;
Point buttonLocation;
int cntButton = 0;
public ButtonArray(Form host)
{
HostForm = host;
}
public void AddButton(int left, int top)
{
Button btnElement = new Button();
btnElement.Top = top;
btnElement.Left = left;
btnElement.Tag = cntButton;
btnElement.Cursor = System.Windows.Forms.Cursors.Default;
btnElement.FlatStyle = System.Windows.Forms.FlatStyle.System;
btnElement.Text = "Button " + cntButton.ToString();
btnElement.Click += new EventHandler(btnElement_Click);
btnElement.MouseDown += new MouseEventHandler(btnElement_MouseDown);
btnElement.MouseMove += new MouseEventHandler(btnElement_MouseMove);
this.Add(cntButton.ToString(), btnElement);
HostForm.Controls.Add(btnElement);
btnElement.BringToFront();
cntButton++;
}
public void RemoveButton(string btnIndex)
{
if (this.Count > 0)
{
HostForm.Controls.Remove((Button)this[btnIndex]);
this.Remove(btnIndex);
}
}
private void btnElement_Click(Object sender, System.EventArgs e)
{
if(null != SelectedButton)
SelectedButton(sender);
}
private void btnElement_MouseDown(object sender, MouseEventArgs e)
{
buttonLocation = e.Location;
}
private void btnElement_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
((Button)sender).Left += e.X - buttonLocation.X;
((Button)sender).Top += e.Y - buttonLocation.Y;
}
}
}
}
frmMain.cs
using System;
using System.Collections;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace ManageControls
{
public partial class frmMain : Form
{
ButtonArray buttonArray;
bool isClicked = false;
Button btnSelected = new Button();
public frmMain()
{
InitializeComponent();
buttonArray = new ButtonArray(this);
this.MouseDown += new MouseEventHandler(frmMain_MouseDown);
buttonArray.SelectedButton += new
SendSelectedButton(buttonArray_SelectedButton);
}
private void buttonArray_SelectedButton(object sender)
{
btnSelected = sender as Button;
}
private void frmMain_MouseDown(object sender, MouseEventArgs e)
{
if (isClicked)
{
buttonArray.AddButton(e.X, e.Y);
this.Cursor = Cursors.Default;
isClicked = false;
}
}
private void tsButton_Click(object sender, EventArgs e)
{
isClicked = true;
this.Cursor = Cursors.Cross;
}
private void tsDelete_Click(object sender, EventArgs e)
{
buttonArray.RemoveButton(btnSelected.Tag.ToString());
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace ManageControls
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmMain());
}
}
}
and the frmMain.Designer.cs
namespace ManageControls
{
partial class frmMain
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.tsMain = new System.Windows.Forms.ToolStrip();
this.AddButton = new System.Windows.Forms.ToolStripButton();
this.toolStripButton1 = new System.Windows.Forms.ToolStripSeparator();
this.RemoveButton = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.openLabel1 = new System.Windows.Forms.ToolStripLabel();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.saveLabel2 = new System.Windows.Forms.ToolStripLabel();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.tsMain.SuspendLayout();
this.SuspendLayout();
//
// tsMain
//
this.tsMain.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.AddButton,
this.toolStripButton1,
this.RemoveButton,
this.toolStripSeparator1,
this.openLabel1,
this.toolStripSeparator2,
this.saveLabel2,
this.toolStripSeparator3});
this.tsMain.Location = new System.Drawing.Point(0, 0);
this.tsMain.Name = "tsMain";
this.tsMain.RenderMode = System.Windows.Forms.ToolStripRenderMode.System;
this.tsMain.Size = new System.Drawing.Size(740, 25);
this.tsMain.TabIndex = 0;
this.tsMain.Text = "toolStrip1";
//
// AddButton
//
this.AddButton.Image = global::ManageControls.Properties.Resources.Button;
this.AddButton.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.AddButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.AddButton.Name = "AddButton";
this.AddButton.Size = new System.Drawing.Size(63, 22);
this.AddButton.Text = "Button";
this.AddButton.Click += new System.EventHandler(this.tsButton_Click);
//
// toolStripButton1
//
this.toolStripButton1.Name = "toolStripButton1";
this.toolStripButton1.Size = new System.Drawing.Size(6, 25);
//
// RemoveButton
//
this.RemoveButton.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center;
this.RemoveButton.Image = global::ManageControls.Properties.Resources.Delete;
this.RemoveButton.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.RemoveButton.ImageTransparentColor = System.Drawing.Color.White;
this.RemoveButton.Name = "RemoveButton";
this.RemoveButton.Size = new System.Drawing.Size(57, 22);
this.RemoveButton.Text = "Delete";
this.RemoveButton.Click += new System.EventHandler(this.tsDelete_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25);
//
// openLabel1
//
this.openLabel1.Name = "openLabel1";
this.openLabel1.Size = new System.Drawing.Size(36, 22);
this.openLabel1.Text = "Open";
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size(6, 25);
//
// saveLabel2
//
this.saveLabel2.Name = "saveLabel2";
this.saveLabel2.Size = new System.Drawing.Size(31, 22);
this.saveLabel2.Text = "Save";
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
this.toolStripSeparator3.Size = new System.Drawing.Size(6, 25);
//
// frmMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(740, 449);
this.Controls.Add(this.tsMain);
this.Name = "frmMain";
this.Text = "Manage Controls - Sample";
this.tsMain.ResumeLayout(false);
this.tsMain.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ToolStrip tsMain;
private System.Windows.Forms.ToolStripButton AddButton;
private System.Windows.Forms.ToolStripButton RemoveButton;
private System.Windows.Forms.ToolStripSeparator toolStripButton1;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripLabel openLabel1;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripLabel saveLabel2;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
}
}
You don't give much information and i'm not going to download your code. But you can create a class which represents the properties that a button can hold such as position / size / text and serialise a collection of this class. Google .NET serialisation and there are hundreds of links on the topic. You can serialise an array and deserialise it easily from a file to dynamically get back all the buttons, then loop through the deserialised collection and add them back to your form.

How to find the tab in a tabcontrol to close it using c# windows application

I have pasted two function from my code. They are for adding a tab in tabcontrol and removing a tab in tabcontrol. Both the functions are inside the same form where tabcontrol resides.
I am able to add the tabs in the tabcontrol with ease. I am calling AddTab() from a another class. And it works perfectly.
I am trying to do the same thing for Removing a tab from another class. But tabpage tp always returns null even though there are still two tabs in my tabcontrol.
what am i missing ??
public void AddTab(string strProcessName)
{
try
{
Global.ExistingTabProcessNames.Add(strProcessName);
this.Show();
//this below line dosent makes duplicate tabs.
TabPage tp = new TabPage();
tp.Text = strProcessName;
tp.Name = strProcessName;
tabControl1.TabPages.Add(tp);
//Activate the newly created Tabpage.
tabControl1.SelectedTab = tp;
tabControl1.ItemSize = new Size(200, 32);
tp.Height = tp.Parent.Height;
tp.Width = tp.Parent.Width;
}
catch (Exception ex)
{
}
}
public void RemoveUnusedTabs(string strTabToRemove)
{
TabPage tp = tabControl1.TabPages[strTabToRemove];
tp.Controls.Remove(this);
tabControl1.TabPages.Remove(tp);
}
I am calling the RemoveUnusedTabs from another class like below..
//create a instance for that class.
Taskbar RemoveTabs = new Taskbar();
RemoveTabs.RemoveUnusedTabs(strTabtoRemove);
I would recommend taking a look at this tab page example for adding/removing tabs.
Here is a simple example:
Form1.cs file:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace TabPageExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void mAddTabButton_Click(object sender, EventArgs e)
{
TabPage new_tab_page = new TabPage();
if (!mTabNameTextBox.Text.Equals(""))
{
new_tab_page.Text = mTabNameTextBox.Text;
new_tab_page.Name = mTabNameTextBox.Text;
mTabControl.TabPages.Add(new_tab_page);
mTabNameTextBox.Text = "";
}
}
private void mRemoveTabButton_Click(object sender, EventArgs e)
{
if (mTabControl.TabPages.Count > 0)
{
TabPage tab_page = mTabControl.TabPages[mTabNameTextBox.Text];
if (tab_page != null)
{
mTabControl.TabPages.Remove(tab_page);
}
}
mTabNameTextBox.Text = "";
}
}
}
Here is Form1.Designer.cs
namespace TabPageExample
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.mTabControl = new System.Windows.Forms.TabControl();
this.mAddTabButton = new System.Windows.Forms.Button();
this.mRemoveTabButton = new System.Windows.Forms.Button();
this.mTabNameTextBox = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// mTabControl
//
this.mTabControl.Location = new System.Drawing.Point(12, 12);
this.mTabControl.Name = "mTabControl";
this.mTabControl.SelectedIndex = 0;
this.mTabControl.Size = new System.Drawing.Size(499, 379);
this.mTabControl.TabIndex = 0;
//
// mAddTabButton
//
this.mAddTabButton.Location = new System.Drawing.Point(162, 408);
this.mAddTabButton.Name = "mAddTabButton";
this.mAddTabButton.Size = new System.Drawing.Size(75, 23);
this.mAddTabButton.TabIndex = 1;
this.mAddTabButton.Text = "Add Tab";
this.mAddTabButton.UseVisualStyleBackColor = true;
this.mAddTabButton.Click += new System.EventHandler(this.mAddTabButton_Click);
//
// mRemoveTabButton
//
this.mRemoveTabButton.Location = new System.Drawing.Point(243, 408);
this.mRemoveTabButton.Name = "mRemoveTabButton";
this.mRemoveTabButton.Size = new System.Drawing.Size(75, 23);
this.mRemoveTabButton.TabIndex = 2;
this.mRemoveTabButton.Text = "Remove Tab";
this.mRemoveTabButton.UseVisualStyleBackColor = true;
this.mRemoveTabButton.Click += new System.EventHandler(this.mRemoveTabButton_Click);
//
// mTabNameTextBox
//
this.mTabNameTextBox.Location = new System.Drawing.Point(194, 444);
this.mTabNameTextBox.Name = "mTabNameTextBox";
this.mTabNameTextBox.Size = new System.Drawing.Size(100, 20);
this.mTabNameTextBox.TabIndex = 3;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(30, 447);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(158, 13);
this.label1.TabIndex = 4;
this.label1.Text = "Enter tab name to Add/Remove";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(523, 476);
this.Controls.Add(this.label1);
this.Controls.Add(this.mTabNameTextBox);
this.Controls.Add(this.mRemoveTabButton);
this.Controls.Add(this.mAddTabButton);
this.Controls.Add(this.mTabControl);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TabControl mTabControl;
private System.Windows.Forms.Button mAddTabButton;
private System.Windows.Forms.Button mRemoveTabButton;
private System.Windows.Forms.TextBox mTabNameTextBox;
private System.Windows.Forms.Label label1;
}
}

Categories

Resources