calling method of parent form in c# - c#

i have opened a mainform and call a child form like
Form4 f = new Form4();
f.Owner = this;
f.Show(this);
in form4, user selects a text file, the contents of which are to be displayed in a textBox1 of mainform
i was trying something like
Owner.textBox1.Text = "file contents";
but it does'nt work

The best way to link different forms together is via events. Create an event in Form4 like FileSelected and then do something like this:
Form4 f = new Form4();
f.FileSelected += (owner, args) => {
textBox1.Text = args.FileName;
};
f.Show(this);

Besides this is really bad design, you need to make textBox1 a public member of your main form and cast f.Owner to the main form type.
Like:
Form4 f = new Form4();
f.Owner = this;
f.Show(this);
// Inside Form4
MainForm main = this.Owner as MainForm;
if (main != null) main.textBox1.Text...

A best practice would be to define yourself a property that would itself set the Text property of your private control. Here's an instance:
public partial class MainForm : Form {
public string ContentDescription {
set {
textBox1.Text = value.trim();
}
}
}
Then after, you'll be able to access this property through type-casting to your particular type:
public partial class SecondaryForm : Form {
public MainForm OwnerForm {
get {
return (MainForm)this.Owner;
}
}
public void someMethod() {
OwnerForm.ContentDescription = "file contents";
}
}
Remember that in C#, every Control is declared private. So, to access it, the best practice is to define a property that will grant you the required access to it. Making a member public is generally not a good idea, depending on what you're trying to achieve.
EDIT For the parse method, perhaps should you consider making it public or internal so that you may access it through the correctly type-casted Owner property of your child form.
Making a hlper class might be the right solution though, so it is not GUI dependent.

In Form4 you can cast Owner to the correct type:
var o = (Form1) this.Owner;
o.textBox1.Text = "file contents";
For this to work, the owner must be of type Form1 and textBox1 on that type must be a public member or property.

As Andrew already gave the correct solution for event driven, there is also a sync (or blocking) method available:
Form4 f = new Form4;
if(f.ShowDialog() == DialogResult.OK)
{
textBox1.Text = f.FileName;
}

You will need to set the "modifiers" to at least public for the properties of the control to be able to have access to it.
alt text http://gabecalabro.com/gabe/Capture.PNG

Related

How to pull data from datagridview to another form's textbox

I am trying to pull the data from a datagridview value in form1 to a textbox in form2 .
Form 1;
public string xxx;
public string GetX()
{
return xxx;
}
private void addADocumentToolStripMenuItem_Click(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows != null)
{
xxx = dataGridView1.CurrentRow.Cells["Name"].Value.ToString();
AddDocumentForm adf = new AddDocumentForm();
adf.ShowDialog();
}
else
{
MessageBox.Show("Please choose a record.");
return;
}
}
In Form 2 trying to pull the xxx value into textbox;
using (Form1 f= new Form1())
{
string result= f.GetX();
txtSavedDocumentID.Text = result;
}
In Form2, you are creating a new instance of Form1:
using (Form1 f= new Form1())
As I can't see your whole code, I might be wrong - but I think it is very likely that this is not what you want.
What you actually want is to call GetX() on an existing instance of Form1.
Now you need some way to know the correct instance of Form1 on Form2. One easy possibility is, but only if you will always just use one instance of Form1, to expose a static property on Form1 that will provide a singleton instance of it to the outside world:
public class Form1
{
// ...
public static readonly Form1 Instance {get; private set};
public Form1()
{
Instance = this;
}
// ...
}
In Form2, instead of creating a new instance with your using statement, you'd access it like this:
string result = Form1.Instance.GetX();
txtSavedDocumentID.Text = result;
Now be aware that if your application has the possibility to have multiple instances of Form1 open, this won't work and will have bad side effects. In this case, another approach is needed. But I hope you got the idea now what might be wrong and you can work it out.
Edit: While this will solve your issue, hopefully, I want to add that it's not a very good approach having your Forms need to know about each other. You should have some model classes in the background where your Forms can read and write data on, without the need to interact with each other directly. But exploring this further would be out of scope of this question.
changed Form2 ;
public Form2(string qs)
{
InitializeComponent();
textBox1.Text = qs;
}
In Form1;
get the text from combobox and pass it to form2 ;
{
var xxxx = (cbxEmployeeName.GetItemText(cbxEmployeeName.SelectedItem));
Form2 f = new Form2(xxxx);
f.Show();
}

TextBox B in Form2 to display text from TextBox A in Form 1 using C# and WinForms

After entering in the appropriate text and pressing enter, I want txtbA text in Form1 to display in txtbB in Form 2.
I already have the key events code written, but I can't seem to figure out the rest.
Visual basic seems to be more straightforward with this, and I am new to C#.
This is using WinForms.
I am really only familiar with visual basic's way of handling this:
txtbA.text = My.Forms.Form2.txbB.text
Thank you for any help you can give!
You can use a static variable
In Form1
public static string txtbAtext
{
get { return txtbAtext ; }
set {txtbAtext = value; }
}
OnTextChanged Event
txtAtext = txtA.Text;
In Form2
Form1 f1 = new Form1();
txtbB.Text = Form1.txtAText;
The simpliest and not very elegant way is to do ist like this:
Make a property in the second form, that can hold a Textbox and set the Text property in the TextChange event of the property in Form2
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public TextBox TextBoxWithSameText { get; set; }
private void textBox2_TextChanged(object sender, EventArgs e)
{
if (TextBoxWithSameText != null)
TextBoxWithSameText.Text = textBox2.Text;
}
}
All you have to do now is to set the property to the Form1.textbox1 when the second form (Form2) is created:
Form2 form = new Form2();
form.TextBoxWithSameText = textbox1;
In order to exchange strings between two Forms classes, you can use a third class. Once added to your project, you need to instantiate this new Class1 in your Form1 and Form2:
Class1 class = new Class1;
Make sure Class1 has a constructor. Now, you can create properties in your Class1, with get and set properties:
public string TextA
{
get
{
return textA;
}
set
{
textA = value;
}
}
You can then call these properties from any other class that has instantiated your Class1, like so:
class.TextA = txtbA.Text;
In order to show the text in the other textbox, you need an event to trigger changing the txtbB.Text value. You could use txtbA.ValueChanged event, or a button with a Click event. You should figure out what event is most appropriate for your project.
I hope this helped! Good luck.
Based on your comment:
Right, Form1 will open an instance of Form2 upon pressing the Enter
key. Thanks!
You can setup Form2 to receive the initial value for the TextBox via its Constructor:
public partial class Form2 : Form
{
public Form2(string InitialValue)
{
InitializeComponent();
this.txtbB.Text = InitialValue;
}
}
Then in Form1 you'd do something like:
Form2 f2 = new Form2(this.txtbA.Text);
f2.Show();

Passing tabConrol properties from on form to another

I am using two forms in a windows form application in C#.I want to pass the tabControl's properties like its "Tabpage count" from first form to second form. Can anyone help me here?I can't create object of first form in second form and call a function beacuse for a new forn object, the tabcontrol gets refreshed.
Inside your first form create an instance of your second Form class as this
Form frm= the instance of your secand form
after that show the instance of your secand form, now you exactly have an instance of your secand form inside your first form and can use all the public properties of it
You can create static public functions exposing desired control properties like in below code.
public static Color TabColor()
{
return Form1.Fom1TabControl1.SelectedTab.ForeColor;
}
and you can access Form1 properties like below;
private void Form2_Load(object sender, EventArgs e)
{
this.Fom2TabControl1.SelectedTab.ForeColor = Form1.ForeColor;
}
First Check your class accessibility and set to public if not work set public static, maybe your namespaces is different
hope it helps
This can be achieved in two ways
Aprroach 1:
Create a public variable in Form2
public int intTabCount=0;
and in Form1, you should call Form2 like
Form2 objForm2 = new Form2();
objForm2.intTabCount = tabPageCountVariable;
objForm2.Show()
Aprroach 2:
Create a parameterized constructor and public variable in Form2
public int intTabCount=0;
public Form2(int TabCounts)
{
intTabCount = TabCounts; // and use intTabCount for your class
}
and call from Form1 like
Form2 objForm2 = new Form2(tabPageCountVariable);
objForm2.Show();
Now if you want to pass value through any events like clicking an button in Form1 which updates anything in Form2, use the below link
Passing Values Between Windows Forms c#

Passing value between forms [duplicate]

How do I pass a value from a child back to the parent form? I have a string that I would like to pass back to the parent.
I launched the child using:
FormOptions formOptions = new FormOptions();
formOptions.ShowDialog();
Create a property (or method) on FormOptions, say GetMyResult:
using (FormOptions formOptions = new FormOptions())
{
formOptions.ShowDialog();
string result = formOptions.GetMyResult;
// do what ever with result...
}
If you're just using formOptions to pick a single value and then close, Mitch's suggestion is a good way to go. My example here would be used if you needed the child to communicate back to the parent while remaining open.
In your parent form, add a public method that the child form will call, such as
public void NotifyMe(string s)
{
// Do whatever you need to do with the string
}
Next, when you need to launch the child window from the parent, use this code:
using (FormOptions formOptions = new FormOptions())
{
// passing this in ShowDialog will set the .Owner
// property of the child form
formOptions.ShowDialog(this);
}
In the child form, use this code to pass a value back to the parent:
ParentForm parent = (ParentForm)this.Owner;
parent.NotifyMe("whatever");
The code in this example would be better used for something like a toolbox window which is intended to float above the main form. In this case, you would open the child form (with .TopMost = true) using .Show() instead of .ShowDialog().
A design like this means that the child form is tightly coupled to the parent form (since the child has to cast its owner as a ParentForm in order to call its NotifyMe method). However, this is not automatically a bad thing.
You can also create a public property.
// Using and namespace...
public partial class FormOptions : Form
{
private string _MyString; // Use this
public string MyString { // in
get { return _MyString; } // .NET
} // 2.0
public string MyString { get; } // In .NET 3.0 or newer
// The rest of the form code
}
Then you can get it with:
FormOptions formOptions = new FormOptions();
formOptions.ShowDialog();
string myString = formOptions.MyString;
You can also create an overload of ShowDialog in your child class that gets an out parameter that returns you the result.
public partial class FormOptions : Form
{
public DialogResult ShowDialog(out string result)
{
DialogResult dialogResult = base.ShowDialog();
result = m_Result;
return dialogResult;
}
}
Use public property of child form
frmOptions {
public string Result; }
frmMain {
frmOptions.ShowDialog(); string r = frmOptions.Result; }
Use events
frmMain {
frmOptions.OnResult += new ResultEventHandler(frmMain.frmOptions_Resukt);
frmOptions.ShowDialog(); }
Use public property of main form
frmOptions {
public frmMain MainForm; MainForm.Result = "result"; }
frmMain {
public string Result;
frmOptions.MainForm = this;
frmOptions.ShowDialog();
string r = this.Result; }
Use object Control.Tag; This is common for all controls public property which can contains a System.Object. You can hold there string or MyClass or MainForm - anything!
frmOptions {
this.Tag = "result": }
frmMain {
frmOptions.ShowDialog();
string r = frmOptions.Tag as string; }
Well I have just come across the same problem here - maybe a bit different. However, I think this is how I solved it:
in my parent form I declared the child form without instance e.g. RefDateSelect myDateFrm; So this is available to my other methods within this class/ form
next, a method displays the child by new instance:
myDateFrm = new RefDateSelect();
myDateFrm.MdiParent = this;
myDateFrm.Show();
myDateFrm.Focus();
my third method (which wants the results from child) can come at any time & simply get results:
PDateEnd = myDateFrm.JustGetDateEnd();
pDateStart = myDateFrm.JustGetDateStart();`
Note: the child methods JustGetDateStart() are public within CHILD as:
public DateTime JustGetDateStart()
{
return DateTime.Parse(this.dtpStart.EditValue.ToString());
}
I hope this helps.
For Picrofo EDY
It depends, if you use the ShowDialog() as a way of showing your form and to close it you use the close button instead of this.Close(). The form will not be disposed or destroyed, it will only be hidden and changes can be made after is gone. In order to properly close it you will need the Dispose() or Close() method. In the other hand, if you use the Show() method and you close it, the form will be disposed and can not be modified after.
If you are displaying child form as a modal dialog box, you can set DialogResult property of child form with a value from the DialogResult enumeration which in turn hides the modal dialog box, and returns control to the calling form. At this time parent can access child form's data to get the info that it need.
For more info check this link:
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.dialogresult(v=vs.110).aspx
i had same problem i solved it like that , here are newbies step by step instruction
first create object of child form it top of your form class , then use that object for every operation of child form like showing child form and reading value from it.
example
namespace ParentChild
{
// Parent Form Class
public partial class ParentForm : Form
{
// Forms Objects
ChildForm child_obj = new ChildForm();
// Show Child Forrm
private void ShowChildForm_Click(object sender, EventArgs e)
{
child_obj.ShowDialog();
}
// Read Data from Child Form
private void ReadChildFormData_Click(object sender, EventArgs e)
{
int ChildData = child_obj.child_value; // it will have 12345
}
} // parent form class end point
// Child Form Class
public partial class ChildForm : Form
{
public int child_value = 0; // variable where we will store value to be read by parent form
// save something into child_value variable and close child form
private void SaveData_Click(object sender, EventArgs e)
{
child_value = 12345; // save 12345 value to variable
this.Close(); // close child form
}
} // child form class end point
} // name space end point
Many ways to skin the cat here and #Mitch's suggestion is a good way. If you want the client form to have more 'control', you may want to pass the instance of the parent to the child when created and then you can call any public parent method on the child.
I think the easiest way is to use the Tag property
in your FormOptions class set the Tag = value you need to pass
and after the ShowDialog method read it as
myvalue x=(myvalue)formoptions.Tag;
When you use the ShowDialog() or Show() method, and then close the form, the form object does not get completely destroyed (closing != destruction). It will remain alive, only it's in a "closed" state, and you can still do things to it.
The fastest and more flexible way to do that is passing the parent to the children from the constructor as below:
Declare a property in the parent form:
public string MyProperty {get; set;}
Declare a property from the parent in child form:
private ParentForm ParentProperty {get; set;}
Write the child's constructor like this:
public ChildForm(ParentForm parent){
ParentProperty= parent;
}
Change the value of the parent property everywhere in the child form:
ParentProperty.MyProperty = "New value";
It's done. the property MyProperty in the parent form is changed. With this solution, you can change multiple properties from the child form. So delicious, no?!

How to prevent a form to show up in the constructor?

I have a C# application and I am trying to prevent a form to show up in the constructor.
I launch the form like this:
Form1 f = new Form1();
f.ShowDialog();
what do I have to do in the Constructor so the f.ShowDialog should not launch and continue code execution.
Can't you add a public property (ShowTheDialog in this example) in the constructor for f and set to true if you want to call f.ShowDialog
Form1 f = new Form1();
if(f.ShowTheDialog) {
f.ShowDialog();
}
I think Pentium10 wants to be able to specify via the constructor whether, at a later time, ShowDialog is allows to actually display a dialog. In other words, he really wants to be able to override ShowDialog, so that in his own ShowDialog he can check this magic permission variable and either bail, or call the base ShowDialog.
I'm not sure if this is technically correct, but it does seem to work. Pentium10, in your Window class, create another public method called ShowDialog that hides the inherited ShowDialog. Then inside, check your variable and only if it's allowed, call the base's ShowDialog method, like this:
public partial class Window3 : Window
{
bool _allowed { get; set; }
public Window3( bool allowed)
{
_allowed = allowed;
InitializeComponent();
}
public void ShowDialog()
{
if( !_allowed)
return;
else
base.ShowDialog();
}
}
(I'm no windows forms expert, but) couldn't you set a flag in your constructor, whether the form can be shown or not, then override the OnLoad() method, and if your flag is false, hide the form immediately, e.g:
private bool _canShow = true;
public Form1()
{
_canShow = ...;
}
protected override OnLoad(EventArgs e)
{
if (!_canShow) Close();
base.OnLoad(e);
}
How about calling ShowDialog in the constructor itself if it needs to be shown ?
And then you only need to do:
Form1 f = new Form1();

Categories

Resources