C# how get a value of richTextBox added to second form - c#

I write program. It's simple editor linke Notepad, created new form in main form, and I don't know how I can get and set value in the richTextField in sub form. When You click New file program use trah function.
private void NewWindow()
{
Form2 f2 = new Form2();
f2.MdiParent = this;
f2.Text = "Document " + WindowNumber.ToString();
WindowNumber++;
f2.Show();
}
When I have many open windows i don't can get to richTextBox in each of window.
How to do that?

Normally, controls are added to forms with the protected acces modifier. Then, to get their values from outside you need to create a public property on each form to expose the text.
public string RichText{
get{ return myTextBox.Text;}
}

i couldn't quite get if you want the parent form to edit the children or the other way around.
if you want the parent to be able to edit the children then the children should expose a method like Oscar example to edit the RichTextBox and the parent should save the children somewhere:
List<Form2> frm = new List<Form2>();
private void NewWindow()
{
Form2 f2 = new Form2();
f2.MdiParent = this;
f2.Text = "Document " + WindowNumber.ToString();
WindowNumber++;
f2.Show();
frm.Add(f2);
}
if the child should edit the parent you have several ways to do it. probably the best one designedly is using Events:
public delegate void EditHandler();
public event EditHandler edit;

Related

How to modify controls from a different form in C#

Is there a way to modify the text in a textbox, or something like that from a different form?
In my program, I need to spawn a new Form2, and have all the textboxes hold information based on stuff entered in Form3. So far I've only done:
Form2 form2 = new Form2();
form2.Show();
I just don't know how to access form2.textbox1.Text, for example, from form3. I've looked online but didn't find quite what I was looking for, and I've tried a few different things with no success.
Thanks! :)
Pass the instance of Form2 into Form3:
public Form3(Form2 referrer)
{
var txt = referrer.TextBox1Text;
}
and then when calling it:
Form3 f3 = new Form3(this);
f3.Show();
and you'll just have to make sure that you build a property on Form2 like this:
internal string TextBox1Text { get { return textBox1.Text; } }
Assuming that you are instantiating the Form2 within the code behind of Form3 (calling "new" Form2())...
You can create a public method within Form2 that will provide the accessibility you need. Example:
(within Form2 - code behind)
public SetTextboxTextProperty(string text)
{
this.Textbox1.Text = text;
}
From Form3:
Form2 form2 = new Form2();
form2.SetTextboxTextProperty("your data");
form2.Show();
The problem is that the controls defined in each form are not public objects, so you can't access them from outside the form.
Why don't you define a public method in each form to retrieve/set the value you need from the controls you need?
I think that it would be a better approach than exposing your controls.

C# Winform close opened window when call other window

How can I close an opened window when I call a new window? That means I want only 1 child window at the time. I don't allow multi-window.
public partial class Main_Usr : Form
{
public Main_Usr()
{
InitializeComponent();
this.IsMdiContainer = true;
if (Program.IsFA) barSubItem_Ordre.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
Ordre_Liste f = new Ordre_Liste();
f.MdiParent = this;
f.Show();
}
private void barButtonItem_CreateOrdre_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
Program.AllerRetour = "Ordre Aller";
Ordre_Fiche f = new Ordre_Fiche();
f.MdiParent = this;
f.Show();
}
private void barButtonItem_OrdreListe_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
Ordre_Liste f = new Ordre_Liste();
f.MdiParent = this;
f.Show();
}
private void barButtonItem_CreateOrdRet_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
Program.AllerRetour = "Ordre Retour";
Ordre_Fiche f = new Ordre_Fiche();
f.MdiParent = this;
f.Show();
}
}
There are different ways to implement pseudo masterpage:
You can create BaseForm form with desired layout. Then inherit other forms from this BaseForm and provide custom content.
You can create MainForm form with desired layout. Then create content controls as UserControls and show them in panel.
You can create MasterUserControl with desired layout. Then create content controls by inheriting from MasterUserControl (they will have same layout). Then use your main form as browser for displaying different content controls like pages.
EXAMPLE:
Create desired layout on Main_Usr form.
Do not set it as MdiContainer
If you want to access some controls (e.g. footer or header from child forms, set property Modifiers of those controls to protected)
Open Ordre_Liste form code and change it to inherit from Main_Usr form, instead of Form
Add custom content to Ordre_Liste form
voila! you have 'masterpage'
UPDATE (for 3rd option)
Create new user control with name MasterUserControl
Create desired layout on this control, keeping space for custom content (btw don't use TableLayoutPanels - they have issue with designer inheritance).
Create new user control with name HomeUserControl and change it to inherit from your MasterUserControl.
Open HomeUserControl designer and add custom content. Also you can modify parent controls, which has protected modifier.
On your main form place HomePageUserControl
There different ways to implement navigation between controls (aka pages). Simplest way - have menu on main form. Other way - define event 'Navigate' on master control, subscribe to that event on main form, and raise it from 'pages'.
Create Form instances on a class level.
Then you can access to them from events or methods.
Form1 f1;
Form2 f2;
void OpenForm1()
{
f1 = new Form1()
f1.Show();
}
void OpenForm2()
{
f1.Dispose(); //or Hide if you want to show it again later
f2 = new Form2();
f2.Show();
}
Like:
List<Form> openForms = new List<Form>();
foreach (Form f in Application.OpenForms)
openForms.Add(f);
foreach (Form f in openForms)
{
if (f.Name != "Menu")
f.Close();
}
Note, do NOT close them directly, becuase there will come to an error, if you would try to close (or dispose) them in the 1st foreach loop. Thats why you need to put them into a list and close them there.

Relationship between the two forms

Methods opening forms :
form1 --> form2 --> form3
ChecklistBox on the form1 there. How to know the form3 That is active or not?
If the forms you are referencing are MDI child forms, you could use
Form activeChild = this.ActiveMdiChild;
else you could use the following code if not using MDI child forms.
Form currentForm = Form.ActiveForm;
I understand that you are asking if form 3 is opened. If that is incorrect, please enlighten me.
There are probably dozens of ways to do so, it all depends on what you want to do.
One simple way would be to leave a flag somewhere, say in your Program.cs file:
public static bool Form3IsOpen = false;
Then:
private void Form3_Load(sender object, EventArgs e)
{
Program.Form3IsOpen = true;
}
And:
private void Form3_Close(sender object, EventArgs e)
{
Program.Form3IsOpen = false;
}
Supplemental:
You can also keep a reference to your subform:
In form1.cs:
private Form2 FormChild;
//In the function that opens the Form2:
FormChild = new Form2();
FormChild.Show();
Form2 will have something similar to retain Form3. If one form can open several, just use an array or collection.
When i usually have many different forms and only one instance to be created, i put them in dictonary and check it if there is a form.
Something like this:
public static Dictonary<string, Form> act_forms_in_app = new Dictonary<string, Form>();
now in every forms creation i do it like this
Form1 frm = new Form1();
frm.Name = "Myformname"
//set its properties etc.
frm.Load => (s,ev) { act_forms_in_app.Add(frm.Name, frm);};
frm.Load += new EventHandler(frm_Load);
frm.Disposed => (s, ev) { act_forms_in_app.Remove(frm.Name)};
//your usual form load event handler
public void frm_Load(object sender, EventArguments e)
{
...
}
somewhere where you want to check
Form frm = //Your form object
if(act_forms_in_app.ContainsKey(frm.Name))
{
//Perform as required
}

MDIWindowListITem Not Working

This one has really got me stumped. I have certain forms that are being instantiated. When I instantiate a form i make it a child of the mdi form by
form1.MdiParent = this;
I have set the MDIWindowListITem property of my menustrip to a toolstripmenuitem
However this toolstripmenuitem does not show the mdi child form when it is instantiated
Does any one have any ideas on this?
Any inputs/ leads / hints would be most welcome. I am using .net framework 3.5
Regards
,
You have to write your code so that it is added manually I believe.
See the example here for pointers:
MSDN help on ToolStripPanel
Edit
You're right ignore my previous entry here's the code for a very simple MDI app that appears to do what your after.
It is just two blank forms. Form1 has IsMDIContainer=true. It also has menuStrip1, which contains two items "new" (newToolStripMenuItem) and "windows" (windowsToolStripMenuItem). Clicking new will open a new child window. I have set the MDIWindowListItem of menuStrip1 to windowsMenuStripItem. When a new child window is opened clicking on windowsMenuStripItem produces a drop down that shows all windows open.
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private int count;
public Form1()
{
InitializeComponent();
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
count++;
//Set a window title text as this is what is shown in the window list.
Form2 newForm = new Form2() { Text = string.Format("Window {0}", count) };
newForm.MdiParent = this;
newForm.Show();//<--- this needed to show window in list.
}
}
}
There is no code in Form2.
The child windows only show below windowMenuStripItem once Form.Show() has been called.
Without this they do not show in the list.

passing something from child form to parent

so i have this form and on it is a combo box populated from a database via a SQL method.
and i have another form which allows us to maintain the database table etc.
so i make a new instance of the second form doing:
Form1 frm = new Form2;
frm.show();
once i have done what ever i wanted to do on the second form and i close it, i need to somehow trigger an event or something which will refresh the combo box and the code behind it.
i was thinking of some onchange or focus event for the whole form, the problem is i have 5 of these combo boxes and running all the SQL again.
i also thought of passing somesort of variable thro but then i would still need an event for that.
any ideals would be awesome
I think you had your answer in the question... Use an event / handler to refresh.
E.g.
public class Form2 : Form
{
public event EventHandler DbChanged;
protected virtual void OnDbChanged()
{
... // Raise event
}
// On OK button/FormClosing/Closed whatever, be sure to call OnDbChanging
}
Then in your Form1 code
var form2 = new Form2();
form2.DbChanged += new EventHandler(Form2_DbChanged); // Add method to handle change and update the appropriate combo box
form2.Show();
If you've assigned these forms with the first form owning the second, like this:
Form2 frm2 = new Form2();
//assuming that you're launching this form from within the first form
frm2.Owner = this;
then you can get a reference to the first form through the Owner property, and thus call methods on it.
Form2_FormClosed(object o, FormClosedEventArgs e)
{
this.Owner.updateComboBox();
}
Note that you'll need the FormClosing event if you want to send data from the form's controls back, though.
Note that the Owner property has some other special characteristics. Notably, the child form will remain showing (on top) when the parent form is selected.
You can use delegate and event here.
Your parent class will create an object of child class and will also subscribe to the event if child class.
Whenever child class need to pass something/ signal parent class, it will raise an event.
As parent has subscribed to these event, it it will get that data and do the required operation.
Hope this helps you.
Forms are classes. Like any other class, they can have properties and events.
Your Form2 can expose a "DatabaseChanged" event. Form1 or any other form that cares can subscribe to that event. When the database changes, Form2 can fire that event, Form1 will see it and update the combo box.
Lots of options, but a simple one is passing the main form as a reference to the second form.
Form2 frm = new Form2( this );
frm.Show();
Then when Form2 finishes its work, it can call some method on the main form to update
public class Form2 : Form
{
public Form2( Form1 form1 )
{
this.form1 = form1;
}
/// ...
public void Work()
{
// ...
form1.Update( someData );
}
}
Not necessarily ideal from a maintenance perspective, but workable for small apps.
Suppose your combo name id cmb1 and
cmb1.DataSource = ds1;
and you need to call a new window do some work there & whenever you close that window your parent will refresh or cmb1 will have the latest data.
from you parent window call your chlid window like this
if (NameOfWindow.RequestAction(ref ds1)) // let RequestAction is a method
{
///refresh your data source of combo
}
and in the child window the method should be like this:
public static bool RequestAction(ref ds1)
{
NameOfWindow frm = new NameOfWindow();
if (frm.ShowDialog() == DialogResult.OK)
{
//do what ever you want to do and update the ds1
return true;
}
else
{
return false;
}
}

Categories