I'm designing a Windows Form to create a child form at run time. I would like that the child form build controls (buttons, list boxes, etc.) depending on a the text entered in the parent form. My problem is when I close the child form, enter new text and relaunch the child form, the same control is being created.
This is how I call the child form:
private void button2_Click(object sender, EventArgs e)
{
try
{
Form2 frm2 = new Form2();
frm2.Show();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This is the code in the child form
try
{
this.MaximizeBox = false;
this.MinimizeBox = false;
this.BackColor = Color.White;
this.ForeColor = Color.Black;
this.Size = new System.Drawing.Size(550, 550);
this.Text = "Test Create form in run time ";
Form1 frm1 = new Form1();
if (frm1.master == "button")
{
this.btnAdd.BackColor = Color.Gray;
this.btnAdd.Text = "Add";
this.btnAdd.Location = new System.Drawing.Point(90, 25);
this.btnAdd.Size = new System.Drawing.Size(50, 25);
this.Controls.Add(btn);
}
}
Can anyone give me a piece of code or link ?
The problem is that you are not sending the text from From1, instead you are creating a new Form1 inside Form2. This is not what you want I guess...
To solve this:
Add a String property in Form2, called say 'ControlText'.
Suppose that the user write the text in a text box called Text1 in
Form1
Then you would call form2 from Form1 like this:
private void button2_Click(object sender, EventArgs e)
{
try
{
Form2 frm2 = new Form2();
frm2.ControlText = Text1.text
frm2.Show();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Finally, the code in form2 will be something like this:
try
{
this.MaximizeBox = false;
this.MinimizeBox = false;
this.BackColor = Color.White;
this.ForeColor = Color.Black;
this.Size = new System.Drawing.Size(550, 550);
this.Text = "Test Create form in run time ";
if (ControlText == "button")
{
this.btnAdd.BackColor = Color.Gray;
this.btnAdd.Text = "Add";
this.btnAdd.Location = new System.Drawing.Point(90, 25);
this.btnAdd.Size = new System.Drawing.Size(50, 25);
this.Controls.Add(btn);
}
}
hope this may help you
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
Utilities.ResetAllControls(this);
}
public class Utilities
{
public static void ResetAllControls(Control form)
{
foreach (Control control in form.Controls)
{
if (control is TextBox)
{
TextBox textBox = (TextBox)control;
textBox.Text = null;
}
if (control is ComboBox)
{
ComboBox comboBox = (ComboBox)control;
if (comboBox.Items.Count > 0)
comboBox.SelectedIndex = 0;
}
if (control is CheckBox)
{
CheckBox checkBox = (CheckBox)control;
checkBox.Checked = false;
}
if (control is ListBox)
{
ListBox listBox = (ListBox)control;
listBox.ClearSelected();
}
}
}
}
Try this
foreach(control in this.Controls)
{
this.Controls.Remove(control);
control.Dispose();
}
this.Controls.Clear();
Related
I have a form. I want to make sure that the RegisterForm.cs form comes as childform when the toggle button I added on this form is activated. It works in a different position from the main panel when I call it normally. Whatever I've done, I haven't been able to solve this problem, can you help me with that?
FormMainMenu.cs
public void OpenChildForm(Form childForm)
{
if (currentChildForm != null)
{
//open only form
currentChildForm.Close();
}
currentChildForm = childForm;
childForm.TopLevel = false;
childForm.FormBorderStyle = FormBorderStyle.None;
childForm.Dock = DockStyle.Fill;
panelDesktop.Controls.Add(childForm);
panelDesktop.Tag = childForm;
childForm.BringToFront();
childForm.Show();
lblTitleChildForm.Text = childForm.Text;
}
SozlesmeFormu.cs
public partial class SozlesmeFormu : Form
{
private bool toggleCheck = false;
public SozlesmeFormu()
{
InitializeComponent();
textBox1.Multiline = true;
textBox1.ScrollBars = ScrollBars.Both;
}
private void toggleSozlesme_CheckedChanged(object sender, EventArgs e)
{
toggleCheck = true;
toggleSozlesme.Enabled = false;
toggleSozlesme.OnBackColor = Color.DarkGray;
this.Close();
FormMainMenu formMain = new FormMainMenu();
formMain.OpenChildForm(new RegisterForm());
}
}
Whatever I did, I couldn't call RegisterForm as childform. It's always irrelevant from the main panel.
I want to create a form programmatically, then add controls to that for and handle click events on those controls,
such as click on button should show impact on text box
namespace formwizard
{
public partial class Form1 : Form
{
Form form = new Form();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
form.Text = formtitle.Text;
int count = Convert.ToInt32(FormName.Text);
int i=1;
while (i<= count)
{
TextBox tb = new TextBox();
tb.Text = "Text box"+ i.ToString();
Button bt = new Button();
bt.Text = "Button" + i.ToString();
tb.Location = new Point(15, i*20);
bt.Location = new Point(120, i*20);
bt.Name = "Button" + i.ToString();
form.Controls.Add(tb);
form.Controls.Add(bt);
bt.Click +=new EventHandler(bt_Click);
i++;
}
// form.Controls.Add(...);
form.ShowDialog();
}
void bt_Click(object sender, EventArgs e)
{
Button btn = (Button) sender;
string a=btn.Text.Substring(6,btn.Text.Length-6);
MessageBox.Show("You clicked Button "+a);
}
}
}
Your code is correct, the only problem I see is you haven't initialized a new instance of Form:
Form form2 = new Form();
//now add your controls to this form
//show form using "form2.ShowDialog()"
my request is suppose i have two sdi form. one sdi main form has button and when user click on that button then a overlay semi transparent window will appear and cover the main sdi form and as well as another sdi will come on top of the over lay window.
here is my overlay window code
namespace CSRAssistant
{
public partial class MaskedDialog : Form
{
static MaskedDialog mask;
static Form frmContainer;
private Form dialog;
private UserControl ucDialog;
private MaskedDialog(Form parent, Form dialog)
{
this.dialog = dialog;
this.FormBorderStyle = FormBorderStyle.None;
this.BackColor = System.Drawing.Color.Black;
this.Opacity = 0.50;
this.ShowInTaskbar = false;
this.StartPosition = FormStartPosition.Manual;
this.Size = parent.ClientSize;
this.Location = parent.PointToScreen(System.Drawing.Point.Empty);
parent.Move += AdjustPosition;
parent.SizeChanged += AdjustPosition;
}
private MaskedDialog(Form parent, UserControl ucDialog)
{
this.ucDialog = ucDialog;
this.FormBorderStyle = FormBorderStyle.None;
this.BackColor = System.Drawing.Color.Black;
this.Opacity = 0.50;
this.ShowInTaskbar = false;
this.StartPosition = FormStartPosition.Manual;
this.Size = parent.ClientSize;
this.Location = parent.PointToScreen(System.Drawing.Point.Empty);
parent.Move += AdjustPosition;
parent.SizeChanged += AdjustPosition;
}
private void AdjustPosition(object sender, EventArgs e)
{
Form parent = sender as Form;
this.Location = parent.PointToScreen(System.Drawing.Point.Empty);
this.ClientSize = parent.ClientSize;
}
//
public static DialogResult ShowDialog(Form parent, Form dialog)
{
mask = new MaskedDialog(parent, dialog);
dialog.StartPosition = FormStartPosition.CenterParent;
mask.MdiParent = parent.MdiParent;
mask.Show();
DialogResult result = dialog.ShowDialog(mask);
mask.Close();
return result;
}
public static DialogResult ShowDialog(Form parent, UserControl dialog)
{
mask = new MaskedDialog(parent, dialog);
frmContainer = new Form();
frmContainer.ShowInTaskbar = false;
frmContainer.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
frmContainer.StartPosition = FormStartPosition.CenterParent;
frmContainer.Height = dialog.Height;
frmContainer.Width = dialog.Width;
frmContainer.Controls.Add(dialog);
mask.MdiParent = parent.MdiParent;
mask.Show();
DialogResult result = frmContainer.ShowDialog(mask);
frmContainer.Close();
mask.Close();
return result;
}
public static void CloseDialog()
{
if (frmContainer != null)
{
frmContainer.Close();
}
}
private void InitializeComponent()
{
this.SuspendLayout();
//
// MaskedDialog
//
this.ClientSize = new System.Drawing.Size(284, 262);
this.Name = "MaskedDialog";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MaskedDialog_FormClosing);
this.Load += new System.EventHandler(this.MaskedDialog_Load);
this.ResumeLayout(false);
}
private void MaskedDialog_Load(object sender, EventArgs e)
{
}
private void MaskedDialog_FormClosing(object sender, FormClosingEventArgs e)
{
}
}
}
this way i am calling my overlay when user click on main sdi button.
Form2 f2 = new Form2();
f2.Show();
MaskedDialog.ShowDialog(this, f2);
f2.Dispose();
f2 = null;
when i am running the code and MaskedDialog.ShowDialog(this, f2); is calling then i am getting a error....the error message is Form that is already visible cannot be displayed as a modal dialog box. Set the form's visible property to false before calling showDialog.
so i am not being able to understand where i am making the mistake. anyone can help me to fix the problem. thanks
You're doing this wrong - call mask.ShowDialog(), not mask.Show() and dialog.ShowDialog(). The error message is pretty clear - you can't ShowDialog a form that's already visible - and that's exactly what you're doing in dialog.ShowDialog(mask);.
Or, in a way that probably more closely shows what you want to do, when calling MaskedDialog.ShowDialog, do this:
Form2 f2 = new Form2();
MaskedDialog.ShowDialog(this, f2);
In other words - don't show the form you're going to ShowDialog. It's going to be made visible by the ShowDialog call.
I am using .NET 3.5 with c# winforms. in this i am using MDI child tab control. it works fine if i open a form, it will open successfully. if i open same form again it opens. that means duplication of tabs.
My code is like below...
private void Main_MdiChildActivate(object sender, EventArgs e)
{
if (this.ActiveMdiChild == null)
tabForms.Visible = false; // If no any child form, hide tabControl
else
{
this.ActiveMdiChild.WindowState = FormWindowState.Maximized; // Child form always maximized
if (this.ActiveMdiChild.Tag == null)
{
TabPage tp = new TabPage(this.ActiveMdiChild.Text);
tp.Tag = this.ActiveMdiChild;
tp.Parent = tabForms;
tabForms.SelectedTab = tp;
this.ActiveMdiChild.Tag = tp;
this.ActiveMdiChild.FormClosed += new FormClosedEventHandler(ActiveMdiChild_FormClosed);
}
if (!tabForms.Visible) tabForms.Visible = true;
}
}
in this, every time this.ActiveMdiChild.Tag takes the value of null so it opens new form again and again. that means duplication of forms in tab control
Add the above method in order to check if the form with the name is as child in the mdi parent.
public static bool FormExist(string formName, out Form frm)
{
frm = null;
bool exist = false;
Form[] f = yourMdiParent.ActiveForm.MdiChildren;
foreach (Form ff in f)
{
if (ff.Name == formName)
{
frm = ff;
exist = true;
break;
}
}
return exist;
}
and add the check on adding the child form.
Form forma;
if(FormExist("yourchildformid",out forma) && forma !=null)
{
forma.Focus();
return;
}
I'm late to the party, but I use:
private void serviceManagerToolStripMenuItem_Click(object sender, EventArgs e)
{
// prevent duplicates
if (Application.OpenForms.OfType<ServiceManager>().FirstOrDefault() != null)
{
return;
}
ServiceManager serviceManager = new ServiceManager { MdiParent = this, WindowState = FormWindowState.Maximized };
serviceManager.Show();
}
I was able to get this to work with a few tweeks by combining other solutions
add this function to your Parent MDI Form
private bool checkTabExists(string tabVal)
{
foreach (TabPage tab in tabForms.TabPages)
{
if (tab.Text == tabVal)
return true;
}
return false;
}
Then Modify the original Form_MdiChildActivate to include an additional check
private void Main_MdiChildActivate(object sender, EventArgs e)
{
if (this.ActiveMdiChild == null)
tabForms.Visible = false; // If no any child form, hide tabControl
else
{
this.ActiveMdiChild.WindowState = FormWindowState.Maximized; // Child form always maximized
if(checkTabExists(this.ActiveMdiChild.Name))
{
//If the Child Form already Exists Go to it
foreach (TabPage tab in tabForms.TabPages)
{
if (tab.Text == this.ActiveMdiChild.Name)
tabForms.SelectedTab = tab;
}
}
// If child form is new and has no tabPage, create new tabPage
else if (this.ActiveMdiChild.Tag == null)
{
ActiveMdiChild.TopLevel = false;
ActiveMdiChild.Dock = DockStyle.Fill;
ActiveMdiChild.FormBorderStyle = FormBorderStyle.None;
// Add a tabPage to tabControl with child form caption
TabPage tp = new TabPage(this.ActiveMdiChild.Text);
tp.Tag = this.ActiveMdiChild;
tp.Parent = tabForms;
tabForms.SelectedTab = tp;
this.ActiveMdiChild.Tag = tp;
this.ActiveMdiChild.FormClosed += new FormClosedEventHandler(Main_FormClosed);
}
if (!tabForms.Visible) tabForms.Visible = true;
//tabForms.AutoSize = true;
//tabForms.TabPages[0].Height = 38;
}
}
I have a form that pops up at a specific event. It draws up buttons from an array and sets the Tag value to a specific value. So if you are to press or click this button the function should return the Tag value.
How can I do this? And how do I know which button was clicked?
At this moment the code returns DialogResult, but I want to return the Tag value from the function. How shall I modify my code so that it can do this?
public static DialogResult SelectBox(string title, string[] btnArray, string[] btnValueArray)
{
Form form = new Form();
Button[] buttonArray;
buttonArray = new Button[5];
form.Text = title;
for (int i = 0; i < btnArray.Length; i++)
{
buttonArray[i] = new Button();
buttonArray[i].Text = btnArray[i];
buttonArray[i].Tag = new int();
buttonArray[i].Tag = btnValueArray[i];
buttonArray[i].TabStop = false;
buttonArray[i].Location = new System.Drawing.Point(0, i * 40);
buttonArray[i].Size = new System.Drawing.Size(240, 40);
}
form.ClientSize = new Size(240, 268);
form.Controls.AddRange(new Control[] { buttonArray[0], buttonArray[1], buttonArray[2] });
form.FormBorderStyle = FormBorderStyle.FixedDialog;
form.StartPosition = FormStartPosition.CenterScreen;
form.MinimizeBox = false;
form.MaximizeBox = false;
DialogResult dialogResult = form.ShowDialog();
return dialogResult;
}
Add a private variable in the form:
private object SelectedTag;
Add a button click handler:
private void Button_Click(object sender, EventArgs e) {
SelectedTag = ((Button)sender).Tag;
}
Assign the handler to each button you create:
..
buttonArray[i].OnClick += form.Button_Click;
..
Then in your static function, simply return form.SelectedTag instead of the dialogresult.
You could call the same click event for all buttons. then in your handler:
private void ButtonClick(object sender, EventArgs args)
{
Button oButton = (Button) sender;
object data = oButton.Tag;
}
The DialogResult property already tells you which button was clicked. You can set each individual button to return a different DialogResult, and then check for that at the bottom of the function.
And if you want to return the clicked button's Tag property instead, you need to change the function's return value to Object (because the Tag property is of type Object).
You can add a ButtonClick event handler in a TestForm, set the button's tag to the Form's tag.
Here is the sample.
Main Form:
private void Form1_Load(object sender, EventArgs e)
{
Object tag;
SelectBox("test", new String[] { "One", "Two", "Three" }, new String[] {"one value", "Two value", "three value" }, out tag);
MessageBox.Show(tag.ToString());
}
public static DialogResult SelectBox(string title, string[] btnArray, string[] btnValueArray, out Object tagValue)
{
TestForm form = new TestForm();
Button[] buttonArray;
buttonArray = new Button[5];
form.Text = title;
for (int i = 0; i < btnArray.Length; i++)
{
buttonArray[i] = new Button();
buttonArray[i].Text = btnArray[i];
buttonArray[i].Tag = new int();
buttonArray[i].Tag = btnValueArray[i];
buttonArray[i].TabStop = false;
buttonArray[i].Location = new System.Drawing.Point(0, i * 40);
buttonArray[i].Size = new System.Drawing.Size(240, 40);
// subscribe to button click event..
// the handler is in TestForm
buttonArray[i].Click += form.HandleOnButtonClick;
}
form.ClientSize = new Size(240, 268);
form.Controls.AddRange(new Control[] { buttonArray[0], buttonArray[1], buttonArray[2] });
form.FormBorderStyle = FormBorderStyle.FixedDialog;
form.StartPosition = FormStartPosition.CenterScreen;
form.MinimizeBox = false;
form.MaximizeBox = false;
DialogResult dialogResult = form.ShowDialog();
// set the out args value
tagValue = form.Tag;
return dialogResult;
}
TestForm that whose instance we create in the SelectBox dialog:
public partial class TestForm : Form
{
public TestForm()
{
InitializeComponent();
}
public void HandleOnButtonClick(Object sender, EventArgs e)
{
Button button = sender as Button;
if (button != null)
this.Tag = button.Tag;
}
}
Edit:
If you want to capture every button's value then expose a Dictionary<String, Object> Tags property.