I have 2 windows Forms, a parent and a child. The parent is the main form. The child is a dialog where the user can edit their details.
When a button is clicked on the parent form, it loads the child form. Like so:
private void add_account_Click(object sender, EventArgs e)
{
this.account_add_edit = new Form2();
account_add_edit.test();
account_add_edit.ShowDialog();
}
As you can see I've created a new form, tried to call a function from the new form, and then showed the form. The problem is the method from the form is not being called. I am getting an error on the IDE that says Windows.Forms.Form does not contain a method test.
I've created the method in the child form:
public static string test(string val)
{
this.username = val;
}
Any ideas as to what I'm doing wrong?
your method is defined as static , so its not posiible to call it on an instace.
you should eaither not make it static, or call it from as static:
Form2.test();
Use:
Form2.test();
static members are associated directly to the class not to its instances. Than means if you need to access a static member you have to access it using it is container type.
More than that, you can not access normal members from static ones. You can only access staticmembers from their peers.
You cannot do the following inside a static method:
this.Member ...
Related
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#
I have a problem with triggering a method in various parent forms from one child form. This child form is used to take user input and pass it to the parent form. Since this input is identical for various types of work (each type is realised in it's own form), I call this child form from various forms.
So far I've solved this problem like this:
In child form there is a piece of code:
private void button3_Click(object sender, EventArgs e)
{
if (Parent.GetType() == typeof(MyType))
{
if ((Parent as MyType).MyFunction()))
{
this.Close();
}
}
}
Parent is a property of type object. This child form is called from a parent form with this code:
MyChildForm IPU = new MyChildForm();
IPU.Parent = this;
IPU.ShowDialog();
The problem with this approach is that I might end up with tens of if-else blocks, one for each type of parent form that need's this child form for input. My question is - is there a way to shorten this code, so that it work's for every type that has a function named MyFunction?
I've tried something like this:
(Parent as typeof(Parent.GetType())).MyFunction()
But I get an error 'Parent is a property but is used like a type'
You can create interface
public interface IParent
{
bool MyFunction();
}
And make Parent property of type IParent. Then make your parent forms implement this interface. Usage will look like:
private void button3_Click(object sender, EventArgs e)
{
if (Parent.MyFunction())
this.Close();
}
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?!
Here is my scenario:
I have a windows form designed in Visual Studio 2010. The form is quite simple. It has 2 text boxes with FirstName and LastName label. And one Display Button.
I have a class name Friend. This class has a Display() method that simply display the first and lastname in a MessageBox.
Now what I am trying to do is:
I instantiate an object "f1" of class Friend at form1_load(object sender, EventArgs e) method. and On the form Display button Click event, I tried to call the Display() method of friend class using f1 object that I instantiate on Form Load event.
But it gave me the error message " The name f1 doesn't exist in the current context."
Is it possible to do what I am trying to do anyway?
Thank You for your help.
Just make it a member variable rather than local:
public class MyForm : Form
{
Friend f1;
private void OnLoad()
{
f1 = new Friend();
}
private void Display()
{
// use f1 here
}
}
I have a Parent Form that holds a "HUD" with First Name, Last Name, etc. One of the child forms is a Search Form. When the user selects a member from the results that are displayed in a DataGrid I want the pertinent information to fill in the HUD. I created a HUD class with variables for each value and a method called UpdateHUD(). I am unsure how to get this working. I have a reference to the Search Form of the Parent form containing the HUD, like so:
public frmWWCModuleHost _frmWWCModuleHost;
This is the code I use to embed forms. I am not using MDI.
public static void ShowFormInContainerControl(Control ctl, Form frm)
{
frm.TopLevel = false;
frm.FormBorderStyle = FormBorderStyle.None;
frm.Dock = DockStyle.Fill;
frm.Visible = true;
ctl.Controls.Add(frm);
}
Here is the code I am running on Cell Click on the Search Form. This is from before I tried implementing the HUD class.
private void dgvSearchResults_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
_frmWWCModuleHost = new frmWWCModuleHost();
_frmWWCModuleHost.tbxHUD_LastName.Text = dgvSearchResults.CurrentRow.Cells[1].FormattedValue.ToString();
_frmWWCModuleHost.tbxHUD_LastName.Invalidate();
_frmWWCModuleHost.FormPaint();
}
Thanks in advance!
~ Patrick
EDIT
dgvSearchResults_CellContentClick is now current. When I step through this code it is getting the correct Value here but it is never updating the actual HUD.
EDIT 2
Is my problem that I am declaring a NEW frmWWCModuleHost instead of passing a ref to the existing? I am still pretty weak in my understanding of this.
EDIT 3
I have "solved" this by doing the following: On the Parent Form where I declare the Child Form I pass this as a param. Then in the constructor of the child form I added _frmWWCModuleHost = m_parent; I have a UpdateHUD() method on my Parent form and I call it from the _CellClick event on the child.
Now to rephrase my question; Is there anything glaringly wrong with doing it this way?
When the child form search completes, raise a "SearchCompleted" event. Then anything (including the parent form) can subscribe to that event and retrieve the details.
See the following NotepadCode for an example:
class ParentForm
{
private readonly ChildForm childForm;
public ParentForm()
{
InitializeComponent();
childForm = new ChildForm();
childForm.SearchCompleted += childForm_SearchCompleted;
}
private void childForm_SearchCompleted(object sender, SearchCompletedEventArgs e)
{
// Update the display
lblName.Text = e.DataToDisplay;
}
}
class ChildForm
{
public event EventHandler<SearchCompletedEventArgs> SearchCompleted;
private void Search(string query)
{
// Do the searching
OnSearchCompleted(new SearchCompletedEventArgs([arg values]));
}
public void OnSearchCompleted(SearchCompletedEventArgs args)
{
if (SearchCompleted != null)
{
SearchCompleted(this, args);
}
}
}
In .NET, Forms are objects like everything else, so you should think of the problem in those terms.
With that, the child form will need access to the parent form. You can provide that by passing the parent form reference to the child form through the constructor, a method, or a field/property (although the constructor makes the most sense).
Then, you can change the values in parent form from the child.
HOWEVER I would say this isn't the best idea. Rather, the child should expose an event indicating that the data changed (as well as the mechanism to get that data) and then the parent should subscribe to that event and update itself with the data when it is fired.
Sometimes in situations like this I'll create a delegate that matches the signature of the method I want to call in the parent class (I think that would be UpdateHUD in your case), and then pass an instance of that delegate (i.e. a reference to UpdateHUD) to the child form (the search form in this case). When the child form is finished accepting input, it invokes the delegate using the data collected on the form.
So, say UpdateHUD is a method in the parent form that looks something like this.
private void UpdateHUD(string firstName, string lastName) {
//...
}
You would create a delegate with the same signature, like this.
public delegate void HUDUpdateHandler(string firstName, string lastName);
Then you would add a HUDUpdateHandler parameter to the constructor of the child form and store it in a private field (for example, this.handler = handler). When your child form is ready to send its data back, you would invoke the child form's private field (this.handler.Invoke(firstNameTextBox.Text, lastNameTextBox.Text), for example). That will invoke UpdateHUD in your parent class using the values from the child class, and you won't have to expose anything.
I find this approach simpler to implement than raising and catching events, and it allows you to keep the internals of your parent class internal.