how to know which form called another form in C# - c#

I am having multiple forms with Buy button provided. The forms i am having are LawnA.cs and Lawnb.cs, i want to use single Buy.cs form for both of these forms. I mean I want to know what form called the Buy.cs.
In Form LawnA.cs
buy.lotAtobuy = this;
buy.ShowDialog();
In Form LawnB.cs
buy.lotBtobuy = this;
buy.ShowDialog();
In Form Buy.cs
public LawnA lotAtobuy;
public LawnB lotBtobuy;
((LawnA)lotAtobuy).textBox1.Text;
((LawnB)lotBtobuy).textBox1.Text;
In class Buy.cs, I want to execute:
((LawnA)lotAtobuy).textBox1.Text;
if LawnA.cs called Buy.cs while if LawnB.cs called Buy.cs I want to execute this code:
((LawnB)lotBtobuy).textBox1.Text;

You need to to define separate object for each class instead for that define the variable as object, and check the type of object before assigning the text. Which means the declaration of that variable in Buy.cs will be:
public object lotToBuyInstance;
So that you can get the type of object and compare before use, that would be like thi:
if (lotToBuyInstance.GetType() == typeof(LawnA))
{
((LawnA)lotAtobuy).textBox1.Text;
}
else if (lotToBuyInstance.GetType() == typeof(LawnB))
{
((LawnB)lotAtobuy).textBox1.Text;
}
// and so on
Consider that you wanted to create another class(let it be some LawnC) then you need not to create an object of that type and make changes as per that, Just add another condition in your if else if ladder to make them work

Try this in the constructor for the receiving form:
using System.Diagnostics;
public FormThatWasCalled
{
string caller = new StackTrace().GetFrame(1).GetMethod().DeclaringType.Name;
InitializeComponent();
}

Related

get control of another window instance

In my WPF program, there is a mask window called CoverP3D needs to be operated (to be maximized or minimized) by different UserControls. The way I call it is to instantiate it in corresponding UserControl back-end code - this causes redundancy because I only need one instance.
CoverP3D cover = new CoverP3D();
...
if (cover.WindowState == WindowState.Minimized)
{
cover.WindowState = WindowState.Maximized;
}
...
I need to create many instances like "cover" in the above code which is redundant. How do I get control of the window that has been already instantiated? Is
Window.GetWindow()
possible? If possible, what dependency object should be its parameter?
Instead of creating a CoverP3D window every time, you need to keep a reference of the created CoverP3D instance and reuse it. like:
public class MainWindow : Window {
private CoverP3D _cover;
CoverP3D Cover {
get {
if (null==_cover)
_cover = new CoverP3D();
return _cover;
}
}
...
}
Then update your code to use the Cover property wherever you want to access the window. like:
if (Cover.WindowState == WindowState.Minimized)
{
Cover.WindowState = WindowState.Maximized;
}
CoverP3D cover = new CoverP3D();
This is a local variable. If you want to share it, you need to put it in a place where it's not lost after the scope ends. As you have not shown as your program there is no way to give you a direct place, but you should put it as a class field somewhere it makes sense. Maybe in your parent window? You say you aren't doing MVVM yet, so it's hard to tell.
Summary: make this variable a field somewhere, so you can share it and not have to recreate it every time.
get control of another window instance
Try this:
CoverP3D coverP3D = (CoverP3D)Application.Current.Windows.OfType<CoverP3D>().FirstOrDefault();
if(coverP3D.Count() > 0)
{
// Do something with existing window
}
else
{
//create new instance
}

Change Textbox object to Static

I have little experience in C#, mostly playing with it as a hobby, and I was wondering what I needed to do to change a textbox from non-static to static.
In Visual Studio 2012, I'm trying to add a line of text using the method textbox1.AppendText("Text");, and it won't work because the textbox isn't static, while the method trying to write the code is static. I can't find the line of code where the textbox is initialized in my code, nor have I found an option in the properties that allows me to change that.
Is there a work-around, or do I need to make it static? And if I need to make it static, how would I do that? I'm at a loss.
Thank you for your help!
EDIT: adding code sample. The method below is called from a second form, same from which the value of x is determined.
public static void getMethod(int x)
{
if (x > 4)
{
textbox1.AppendText("Text");
}
else
{
textbox1.AppendText("Other text");
otherVariable = x;
}
}
It's not clear from your post which GUI framework you're using. Both Winforms and WPF have a TextBox class.
But, to the point of your question: you could in the object where the TextBox is declared and created, also have a static field to which you assign that reference. But that would be a poor design choice, IMHO.
It's not clear what your static code is doing, where it's declared, or who called it (another failing of your question is that you did not provide any code, never mind a concise, complete code example), but assuming the static method is not in the UI object that owns the TextBox instance itself (if it is, then you just need to make the method non-static), the the correct way to address this would be for the UI object that does know about the TextBox instance to have some public method or property used to set the text, and then for the code that invokes your static method to pass the reference of that UI object to the static method, so that it can use the member you added.
For example:
class Form1 : Form
{
public string FieldText
{
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
}
and elsewhere:
static void SomeMethod(Form1 form)
{
// ...do some stuff...
form.FieldText = "some text";
// ...do some other stuff...
}
In your specific scenario, you seem to have two forms: one containing the textbox1 member, and another that passes an int value to a method, where you want to be able to add some text to the TextBox1 based on the value.
In that case, it would look more like this:
class Form1 : Form
{
public void AppendFieldText(string text)
{
textbox1.AppendText(text);
}
}
and in the static method:
public static void getMethod(int x, Form1 form)
{
if (x > 4)
{
form.AppendFieldText("Text");
}
else
{
form.AppendFieldText("Other text");
otherVariable = x;
}
}
Naturally, the caller of the getMethod() method will need the reference for the form parameter; you will have to pass that somehow to that second form which is calling this method, so that it can pass it to the method.
Note that in both of my examples, I have not exposed the TextBox object itself. You should follow this example, exposing only the minimum amount of functionality needed in order to get the job done. This helps ensure that the TextBox object doesn't wind up getting used in appropriately by some other code, and especially helps ensure that your classes remain reasonably decoupled.
On that latter point, I will mention that your code example is still pretty bare. There are other techniques which can solve this problem with even less coupling between the types. But again, lacking a good code example, it's not possible to know for sure what would work, never mind what would be best.
The above example is appropriate, given the information you've shared.
If you would like to edit your question to provide better, more specific detail, a better, more specific answer could be provided.
you can do something like below
private void button3_Click(object sender, EventArgs e)
{
getMethod(textBox1,5);
}
public static void getMethod(TextBox textbox1,int x)
{
if (x > 4)
{
textbox1.AppendText("Text");
}
else
{
textbox1.AppendText("Other text");
otherVariable = x;
}
}
Textboxes aren't static. And you can't make them static, they are all instanciated. The name of your textbox is the instance name.
So just use the text property on the instance of the text box.
textbox1.Text = "Text";
If you want to Append one just do:
textbox1.Text = String.Concat(Textbox1.Text, "more text");
same thing about could also be seen as:
textbox1.Text = textbox1.Text + "more text";

passing variables form to form private to global in c#?

Been working on a simple c# windows app program. I have been able to pass a few variables from one form to the next and use them using form2 y = new form2(passingVariable); y.ShowDialog(); and then on the next form public form2(string myVariable). However this method only allows me to use the variable within those curly braces. Currently I am trying to pass it to the next form in line. However it won't let me use the variable when I try to pass it into the next form using the code line I provided above. It gives me the error The name 'userName' does not exist in the current context I have a lot of source code and didn't know what exactly was needed for me to share so here is the link to my webng.com account with a very simple web page set up with my source code if anyone needs to review it.
Try creating another variable on that current form to store that Username and then assign the username passed into that variable. Your constructor will be like this then:
private string username;
public talkingWithProgram(string userName, string pcName)
{
InitializeComponent();
this.Text = pcName;
programQuestion.Text = "Whatcha wanna talk about \n" + userName + "?";
this.userName = userName;
}
sportsCategories y = new sportsCategories(userName);
Creating a new sportsCategories class now passes userName from this context, which has the value from the previous form. Currently it looks like you're referring to the userName in the constructor which is in the method context and out of scope outside.
I would avoid setting specific variables in the constructor of a windows form. In general, it is more customary to use getters and setters, or a function designated specifically for this purpose.
For example: If you can have the code form2 y = new form2(passingVariable); instead you can have the code
form2 y = new form2();
form2.SetMyVar(passingVariable);
OR, if you are using getters and setters:
form2 y = new form2();
form2.SetMyVar = passingVariable
That way, whenever you need to set or update the variable you can do it as long as you have a reference to the form. Also, in said SetMyVar() function (if you choose that method), be sure to set a class variable. In your code, class variables go outside your functions, so that they are visible to all functions of that instance of the class.
initialize a variable in a class xyz
assign the values to them in constructor like
String a1,b1=String.empty
Class xyz
{
xyz(string a,string b)
{ //constructor
a1=a;
b1=b;
//Now use them in whole class
}
}
or if you want to use them in whole application then initialize them globally in Program.cs
then you can set and get values like
Program.a1="abc" //assigning value

How to set text in form from another form?

I'm working on a term paper that performs operations with complex numbers. Application looks like this:
If you click on "Calculate", will calculate the operands and the result is displayed in a new dialog box. So I have two dialogs - a main window (up on pic) to display the read result (down on pic). Unfortunately I was not able to save result in the main dialog box, which is then written to a text file. There is important piece of code:
Thank you for ideas.
In your MainForm class declare a property as
public class MainForm:Form
{
public string CalculationResult { get; set; }
...
...
//Your code here
...
...
}
then on method of calculate change it to
if(resultBool!=null)
{
CalculationResult = resultBool.ToString());
formResult dlg=new formResult(CalculationResult);
dlg.Owner=this
dlg.StartPosition=FormStartPosition.CenterParent;
dlg.ShowDialog();
}
else
{
...
...
//your code
...
...
}
and change the following line
sw.WriteLine("Result: ");
to
sw.WriteLine("Result: " + CalculationResult);
in saveData method which is in MainForm class. Hope this will work for you. Happy coding
You have to use a reference on the target form to write on it.
You have to assure that you use the correct targetForm reference. You could either create a new targetForm or use an existing one. You could for example use the "parent" form of your dialog box and set the text of the main form textbox, from a dialog box event (using this as MSDN reference):
Dim targetForm As Form = Me.parentForm
targetForm.targetTextBox.Text = "text"
Hope I helped!
In formResult create a variable which keep a reference of Main form
private MyMainForm _mainForm;
Then create one more constructor which take reference of your Main form as parameter:
public formResult(MyMainForm mainform)
{
this.InitializeComponent();
this._mainForm = mainform;
//Now you have access to public property ResultOut
this.textBoxResult.Text = this._mainForm.ResultOut;
}
After this you can use all public properties and method of your main form in second form(formResult)

Single reusable function to open a single instance of form

I am trying to create a reusable function that can open a single instance of form. Means if a form is not already open it should create and show the new form and if already open it should bring the existing form to front.
I was using the following function,
if (Application.OpenForms["FPSStorageDemo"] == null)
{
FPSStorageDemo fp = new FPSStorageDemo();
fp.Name = "FPSStorageDemo";
fp.Show();
}
else
{
((FPSStorageDemo)Application.OpenForms["FPSStorageDemo"]).BringToFront();
}
But I have to write this code again and again whereever I have to open a form. But I need a single reusable function that can do this job.
I wrote a function like,
void OpenSingleInstanceForm(Type TypeOfControlToOpen)
{
bool IsFormOpen = false;
foreach (Form fm in Application.OpenForms)
{
if (fm.GetType() == TypeOfControlToOpen)
{
IsFormOpen = true;
fm.BringToFront();
break;
}
}
if (!IsFormOpen)
{
Object obj = Activator.CreateInstance(TypeOfControlToOpen);
//obj.Show(); //Here is the problem
}
}
But at the end I don't know how to show the new form instance. Can anybody suggest how to do it? Is this wrong or there is another way to do this?
Thanks in advance.
public static class FormUtility
{
public static FormType GetInstance<FormType>() where FormType : Form, new()
{
FormType output = Application.OpenForms.OfType<FormType>().FirstOrDefault();
if(output == null)
{
output = new FormType();
}
//you could add the show/bring to front here if you wanted to, or have the more general method
//that just gives a form that you can do whatever you want with (or have one of each).
return output;
}
}
//elsewhere
FormUtility.GetInstance<Form1>.BringToFront();
I'd also like to take the time to mention that while having methods like this are quick and easy to use, in most cases they are not good design. It leads you to the practice of just accessing forms globally rather than ensuring that when forms need to communicate with each other they do so by exposing the appropriate information through the appropriate scope. It makes programs easier to maintain, understand, extend, increases reusability, etc. If you have trouble determining how best for two or more forms to communicate without resorting to public static references to your forms (which is exactly what Application.OpenForms is) then you should feel free to post that question here for us to help you solve.
You are looking for Singleton
Check this Implementing Singleton in C#

Categories

Resources